如何使用Python将目录更改回原始工作目录?

时间:2022-02-14 20:12:16

I have a function that resembles the one below. I'm not sure how to use the os module to get back to my original working directory at the conclusion of the jar's execution.

我有一个类似下面的功能。我不确定如何在jar执行结束时使用os模块返回到我原来的工作目录。

def run(): 
    owd = os.getcwd()
    #first change dir to build_dir path
    os.chdir(testDir)
    #run jar from test directory
    os.system(cmd)
    #change dir back to original working directory (owd)

note: I think my code formatting is off - not sure why. My apologies in advance

注意:我认为我的代码格式化是关闭的 - 不知道为什么。我提前道歉

5 个解决方案

#1


18  

You simply need to add the line:

您只需添加以下行:

os.chdir(owd)

Just a note this was also answered in your other question.

请注意,您的其他问题也回答了这个问题。

#2


17  

A context manager is a very appropriate tool for this job:

上下文管理器是这项工作的一个非常合适的工具:

from contextlib import contextmanager

@contextmanager
def cwd(path):
    oldpwd=os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(oldpwd)

...used as:

os.chdir('/tmp') # for testing purposes, be in a known directory
print 'before context manager: %s' % os.getcwd()
with cwd('/'):
    # code inside this block, and only inside this block, is in the new directory
    print 'inside context manager: %s' % os.getcwd()
print 'after context manager: %s' % os.getcwd()

...which will yield something like:

...会产生类似的东西:

before context manager: /tmp
inside context manager: /
after context manager: /tmp

This is actually superior to the cd - shell builtin, inasmuch as it also takes care of changing directories back when a block is exited due to an exception being thrown.

这实际上优于cd-shell内置,因为它还会在由于抛出异常而退出块时更改目录。


For your specific use case, this would instead be:

对于您的特定用例,这将是:

with cwd(testDir):
    os.system(cmd)

Another option to consider is using subprocess.call() instead of os.system(), which will let you specify a working directory for the command to run:

另一个需要考虑的选择是使用subprocess.call()而不是os.system(),它将允许您为要运行的命令指定工作目录:

# note: better to modify this to not need shell=True if possible
subprocess.call(cmd, cwd=testDir, shell=True)

...which would prevent you from needing to change the interpreter's directory at all.

...这将阻止您根本不需要更改解释器的目录。

#3


8  

The advice to use os.chdir(owd) is good. It would be wise to put the code which needs the changed directory in a try:finally block (or in python 2.6 and later, a with: block.) That reduces the risk that you will accidentally put a return in the code before the change back to the original directory.

使用os.chdir(owd)的建议很好。将需要更改目录的代码放在try:finally块中(或者在python 2.6及更高版本中,使用:block。)这样可以降低在更改之前意外地在代码中返回的风险回到原来的目录。

def run(): 
    owd = os.getcwd()
    try:
        #first change dir to build_dir path
        os.chdir(testDir)
        #run jar from test directory
        os.system(cmd)
    finally:
        #change dir back to original working directory (owd)
        os.chdir(owd)

#4


2  

os.chdir(owd) should do the trick (like you've done when changing to testDir)

os.chdir(owd)应该这样做(就像你在更改为testDir时所做的那样)

#5


1  

Python is case sensitive so when typing the path make sure it's the same as the directory you want to set.

Python区分大小写,因此在键入路径时请确保它与您要设置的目录相同。

import os

os.getcwd()

os.chdir('C:\\')

#1


18  

You simply need to add the line:

您只需添加以下行:

os.chdir(owd)

Just a note this was also answered in your other question.

请注意,您的其他问题也回答了这个问题。

#2


17  

A context manager is a very appropriate tool for this job:

上下文管理器是这项工作的一个非常合适的工具:

from contextlib import contextmanager

@contextmanager
def cwd(path):
    oldpwd=os.getcwd()
    os.chdir(path)
    try:
        yield
    finally:
        os.chdir(oldpwd)

...used as:

os.chdir('/tmp') # for testing purposes, be in a known directory
print 'before context manager: %s' % os.getcwd()
with cwd('/'):
    # code inside this block, and only inside this block, is in the new directory
    print 'inside context manager: %s' % os.getcwd()
print 'after context manager: %s' % os.getcwd()

...which will yield something like:

...会产生类似的东西:

before context manager: /tmp
inside context manager: /
after context manager: /tmp

This is actually superior to the cd - shell builtin, inasmuch as it also takes care of changing directories back when a block is exited due to an exception being thrown.

这实际上优于cd-shell内置,因为它还会在由于抛出异常而退出块时更改目录。


For your specific use case, this would instead be:

对于您的特定用例,这将是:

with cwd(testDir):
    os.system(cmd)

Another option to consider is using subprocess.call() instead of os.system(), which will let you specify a working directory for the command to run:

另一个需要考虑的选择是使用subprocess.call()而不是os.system(),它将允许您为要运行的命令指定工作目录:

# note: better to modify this to not need shell=True if possible
subprocess.call(cmd, cwd=testDir, shell=True)

...which would prevent you from needing to change the interpreter's directory at all.

...这将阻止您根本不需要更改解释器的目录。

#3


8  

The advice to use os.chdir(owd) is good. It would be wise to put the code which needs the changed directory in a try:finally block (or in python 2.6 and later, a with: block.) That reduces the risk that you will accidentally put a return in the code before the change back to the original directory.

使用os.chdir(owd)的建议很好。将需要更改目录的代码放在try:finally块中(或者在python 2.6及更高版本中,使用:block。)这样可以降低在更改之前意外地在代码中返回的风险回到原来的目录。

def run(): 
    owd = os.getcwd()
    try:
        #first change dir to build_dir path
        os.chdir(testDir)
        #run jar from test directory
        os.system(cmd)
    finally:
        #change dir back to original working directory (owd)
        os.chdir(owd)

#4


2  

os.chdir(owd) should do the trick (like you've done when changing to testDir)

os.chdir(owd)应该这样做(就像你在更改为testDir时所做的那样)

#5


1  

Python is case sensitive so when typing the path make sure it's the same as the directory you want to set.

Python区分大小写,因此在键入路径时请确保它与您要设置的目录相同。

import os

os.getcwd()

os.chdir('C:\\')