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