【问题标题】:How do I change directory back to my original working directory with Python?如何使用 Python 将目录更改回原来的工作目录?
【发布时间】:2008-11-18 17:19:47
【问题描述】:

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

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

【问题讨论】:

  • 如果您在代码的每一行之前放置四个空格,SO 会更好地格式化它。
  • 我刚刚为@Amara 修复了这个问题 :) .. 他们使用
     标签打开,但使用  结束。不过,现在一切都很干净和快乐:D

标签: python


【解决方案1】:

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

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)

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

【讨论】:

  • 感谢 .call(cwd=...) 的想法!
【解决方案2】:

您只需添加以下行:

os.chdir(owd)

请注意,您的其他 question 也已回答了此问题。

【讨论】:

  • 注明。 :) 我想确保我的问题更加具体和详细,以便获得最佳帮助,并且发布代码示例以使我的问题更加清晰。
【解决方案3】:

对于这种情况(执行系统命令),上下文管理器是多余的。最好的解决方案是改用subprocess 模块(Python 2.4 及更高版本)和带有cwd 参数的runpopen 方法。

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

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

【讨论】:

    【解决方案4】:

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

    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)
    

    【讨论】:

      【解决方案5】:

      os.chdir(owd) 应该可以解决问题(就像您在更改为 testDir 时所做的那样)

      【讨论】:

        【解决方案6】:

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

        import os
        
        os.getcwd()
        
        os.chdir('C:\\')
        

        【讨论】:

        • 我不确定是 Python 是否区分大小写,我认为是操作系统(Linux 等)。
        猜你喜欢
        • 1970-01-01
        • 2011-10-22
        • 1970-01-01
        • 2010-11-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-14
        • 1970-01-01
        相关资源
        最近更新 更多