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

时间:2008-11-18 17:19:48

标签: python

我有一个类似下面的功能。我不确定如何在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)

注意:我认为我的代码格式化已关闭 - 不确定原因。我提前道歉

6 个答案:

答案 0 :(得分:24)

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

from contextlib import contextmanager

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

...用作:

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()

......这会产生类似的结果:

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

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

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

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

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

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

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

答案 1 :(得分:20)

您只需添加以下行:

os.chdir(owd)

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

答案 2 :(得分:10)

使用os.chdir(owd)的建议很好。将需要更改目录的代码放在try:finally块中(或者在python 2.6及更高版本中,with:块中)是明智的。这样可以降低意外放置{{}的风险。 1}}在更改回原始目录之前的代码中。

return

答案 3 :(得分:2)

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

答案 4 :(得分:1)

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

import os

os.getcwd()

os.chdir('C:\\')

答案 5 :(得分:0)

在这种情况下(执行系统命令),上下文管理器是多余的。最好的解决方案是改为使用subprocess模块(从Python 2.4开始)和带有run参数的popencwd方法。

因此,您的代码可以替换为:

def run(): 
    #run jar from test directory
    subprocess.run(cmd, cwd=testDir)

请参见https://bugs.python.org/issue25625https://docs.python.org/3/library/subprocess.html#subprocess-replacements