import os
class cd:
"""Context manager for changing the current working directory"""
def __init__(self, newPath):
self.newPath = os.path.expanduser(newPath)
def __enter__(self):
self.savedPath = os.getcwd()
os.chdir(self.newPath)
def __exit__(self, etype, value, traceback):
os.chdir(self.savedPath)
import subprocess # just to call an arbitrary command e.g. 'ls'
# enter the directory like this:
with cd("~/Library"):
# we are in ~/Library
subprocess.call("ls")
# outside the context manager we are back wherever we started.
您可以使用以下命令更改工作目录:
使用此方法时,有两个最佳实践可遵循:
更改子进程中的当前工作目录不会更改父进程中的当前工作目录。Python解释器也是如此。不能使用
os.chdir()
更改调用进程的CWD。下面是一个上下文管理器更改工作目录的示例。它比其他地方引用的ActiveState version更简单,但这可以完成任务。
上下文管理器:
cd
或者使用ContextManager尝试more concise equivalent(below)。
示例
我会像这样使用
os.chdir
:顺便说一下,如果您需要确定当前路径,请使用
os.getcwd()
。更多here
相关问题 更多 >
编程相关推荐