叮当猫咪
下面是一个更改工作目录的上下文管理器的示例。它比一个ActiveState版本提到其他地方,但这就完成了任务。上下文管理器:cdimport osclass 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)或者尝试更简洁的等价物(见下文),使用ContextManager.例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.