我有一个类似下面的功能.我不确定如何在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)
Run Code Online (Sandbox Code Playgroud)
注意:我认为我的代码格式是关闭的 - 不知道为什么.我提前道歉
Cha*_*ffy 26
上下文管理器是这项工作非常合适的工具:
from contextlib import contextmanager
@contextmanager
def cwd(path):
oldpwd=os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(oldpwd)
Run Code Online (Sandbox Code Playgroud)
...用作:
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()
Run Code Online (Sandbox Code Playgroud)
...会产生类似的东西:
before context manager: /tmp
inside context manager: /
after context manager: /tmp
Run Code Online (Sandbox Code Playgroud)
这实际上是优越的cd -
shell内建的,因为它也需要照顾,当块退出目录切换回因抛出异常.
对于您的特定用例,这将是:
with cwd(testDir):
os.system(cmd)
Run Code Online (Sandbox Code Playgroud)
另一个需要考虑的选项是使用subprocess.call()
而不是os.system()
,它将允许您为要运行的命令指定工作目录:
# note: better to modify this to not need shell=True if possible
subprocess.call(cmd, cwd=testDir, shell=True)
Run Code Online (Sandbox Code Playgroud)
...这将阻止您根本不需要更改解释器的目录.
Ale*_*try 11
使用建议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)
Run Code Online (Sandbox Code Playgroud)
您现在可以简单地使用contextlib.chdir
stdlib 中的内容。它在进入块时更改目录,然后恢复旧目录:
from contextlib import chdir
from os import getcwd
print(f"Before: {getcwd()}")
with chdir("/"):
print(f"inside: {getcwd()}")
print(f"after: {getcwd()}")
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
22761 次 |
最近记录: |