A context to change current working directory.

Gribouillis 0 Tallied Votes 589 Views Share

This snippet defines a context to execute a block of statements in a different working directory (with the help of the with statement). After the block is exited, the initial working directory is restored, even if an exception has occurred in the with block.

# a context to change working directory
# tested with python 2.6 and 3.1. For 2.5, uncomment this:
# from __future__ import with_statement
from contextlib import contextmanager
import os

@contextmanager
def WorkingDirectory(dst_dir):
    dst_dir = os.path.abspath(
            os.path.normpath(
            os.path.expanduser(
            os.path.expandvars(dst_dir))))
    current_dir = os.getcwd()
    os.chdir(dst_dir)
    try:
        yield dst_dir
    finally:
        os.chdir(current_dir)


if __name__ == "__main__":
    # test code
    with WorkingDirectory(".."):
        # code in this with block is executed with
        # the parent dir as current working directory
        print(os.getcwd())
    # after the with block, we are back in the
    # initial working directory. This is also
    # true if an exception is raised inside the with block.
    print(os.getcwd())