python - 如何使用 Python 将目录更改回原来的工作目录?

标签 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)

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

最佳答案

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

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(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 - shell 内置的优越,因为它还负责在由于抛出异常而退出 block 时将目录更改回来。


对于您的特定用例,改为:

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),但可以使用相同的参数,尤其是 cwd: https://docs.python.org/3/library/subprocess.html#using-the-subprocess-module .

关于python - 如何使用 Python 将目录更改回原来的工作目录?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/299446/

相关文章:

python - 根据 bool 向量组合 2 个 pandas 数据帧

python - 如何从图像中读取标点符号,如 '/' 、 '_' 和 '\'

python - 如何使用 wxPython 创建具有 alpha channel 透明度的窗口?

python - 给出基本的 boto create_qualification_type 示例

python 列表理解 : return a list of strings instead of a list of lists

python - 从字符串中提取 Python 字典

javascript - 如何使用 python selenium 单击位于 html 页面列表中没有唯一标识符的文本?

python - MultiIndex 数据帧的平均值

python - 如何使用具有相同类名的scrapy抓取内容

python - 如何修补 python 方法以运行测试用例?