Posted By

ches on 07/16/11


python Blocks

Versions (?)

chdir context manager

 / Published in: Python


This context manager restores the value of the current working directory (cwd) after the enclosed code block completes or raises an exception. If a directory name is supplied to the context manager then the cwd is changed prior to running the code block.

  1. from __future__ import with_statement # only for python 2.5
  2. import contextlib
  3. import os
  5. @contextlib.contextmanager
  6. def chdir(dirname=None):
  7. curdir = os.getcwd()
  8. try:
  9. if dirname is not None:
  10. os.chdir(dirname)
  11. yield
  12. finally:
  13. os.chdir(curdir)

Report this snippet  

You need to login to post a comment.