如何使用Python将目录更改回原始工作目录?
我有一个类似于下面的函数。我不知道如何在jar执行结束时使用os模块返回到我原来的工作目录如何使用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)
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)
注意:我想我的代码格式是关闭的-不知道为什么。我提前道歉您只需添加一行:
os.chdir(owd)
只需注意,这一点在您的另一本书中也得到了回答。
os.chdir(owd)
的建议很好。明智的做法是将需要更改目录的代码放在try:finally
块中(或在python 2.6及更高版本中,放在with:
块中),这样可以降低在更改返回到原始目录之前意外将返回
放在代码中的风险
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)
Python区分大小写,因此在键入路径时,请确保它与目录相同 你要设置
import os
os.getcwd()
os.chdir('C:\\')
上下文管理器是非常适合此工作的工具:
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)
另一个要考虑的选项是使用<代码>子进程.Car())/>代码>而不是<代码> OS.St体系()/<代码>,这将允许您为运行的命令指定一个工作目录:
# note: better to modify this to not need shell=True if possible
subprocess.call(cmd, cwd=testDir, shell=True)
…这将使您根本不需要更改解释器的目录。上下文管理器在这种情况下(执行一个系统命令)太过灵活了。最好的解决方案是使用
子流程
模块(Python2.4以后的版本)和run
或popen
方法以及cwd
参数
因此,您的代码可以替换为:
def run():
#从测试目录运行jar
subprocess.run(cmd,cwd=testDir)
请参阅和。如果您在代码的每行前面加上四个空格,那么会使代码的格式更精确。我刚刚为@Amara:)修复了这个问题。。他们用一个标签打开,但用一个结束。不过,现在一切都干净愉快了:达尔索回答说。注意:)为了得到最好的帮助,我想确保我的问题更具体、更详细,同时,我还发布了一个代码示例,让我的问题更加清晰。感谢.call(cwd=…)的想法!