如何用Python返回到原始工作目录?

41 投票
8 回答
59237 浏览
提问于 2025-04-11 19:49

我有一个函数,跟下面这个差不多。我不太确定怎么用os模块在jar执行完后返回到我最初的工作目录。

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)

注意:我觉得我的代码格式可能有点问题,不太清楚为什么。提前向大家道歉。

8 个回答

17

建议使用 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)
79

上下文管理器是一个非常合适的工具来完成这个任务:

from contextlib import contextmanager
import os

@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(f'before context manager: {os.getcwd()}')
with cwd('/'):
    # code inside this block, and only inside this block, is in the new directory
    print(f'inside context manager: {os.getcwd()}')

print(f'after context manager: {os.getcwd()}')

...这样会得到类似于:

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

实际上,这种方法比 cd - 这个命令要更好,因为它还会在遇到异常时自动帮你切换回之前的目录。


对于你的具体需求,可以这样做:

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)

...这样就不需要手动切换解释器的目录了。

需要注意的是,现在推荐使用 subprocess.run(而不是 call),但参数是一样的,特别是 cwdhttps://docs.python.org/3/library/subprocess.html#using-the-subprocess-module

34

你只需要添加这一行:

os.chdir(owd)

顺便提一下,这个问题在你另外一个提问中也有回答。

撰写回答