Skip to content

Instantly share code, notes, and snippets.

@harmy
Created June 9, 2015 17:24
Show Gist options
  • Save harmy/46bd57c9e5f674fa6c90 to your computer and use it in GitHub Desktop.
Save harmy/46bd57c9e5f674fa6c90 to your computer and use it in GitHub Desktop.
A context manager which changes the working directory to the given path, and then changes it back to its previous value on exit.
@contextlib.contextmanager
def working_directory(path):
"""
A context manager which changes the working directory to the given
path, and then changes it back to its previous value on exit.
Original by Greg Warner:
http://code.activestate.com/recipes/576620-changedirectory-context-manager/#c3
"""
prev_cwd = os.getcwd()
os.chdir(path)
try:
yield
finally:
os.chdir(prev_cwd)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment