import contextlib
import os
@contextlib.contextmanager
def pushd(new_dir):
previous_dir = os.getcwd()
os.chdir(new_dir)
try:
yield
finally:
os.chdir(previous_dir)
with pushd('somewhere'):
print os.getcwd() # "somewhere"
print os.getcwd() # "wherever you started"
通过这种写法,能够避免反复写 os.chdir(新目录), os.chdir(原有目录) 的组合,减少代码、减少出错。
参考:https://stackoverflow.com/a/13847807/4394850