[Python-ideas] chdir context manager

Vinay Sajip vinay_sajip at yahoo.co.uk
Sat Jan 19 14:46:26 CET 2013


Daniel Shahaf <d.s at ...> writes:

> Joao S. O. Bueno wrote on Sat, Jan 19, 2013 at 10:17:57 -0200:
> > with temp_dir("/tmp"):
> >     # things that perform in  /tmp
> > # directory is restored.
> 
> +1

I implemented this in distlib as:

@contextlib.contextmanager
def chdir(d):
    cwd = os.getcwd()
    try:
        os.chdir(d)
        yield
    finally:
        os.chdir(cwd)

which could perhaps be placed in shutil, so usage would be:

with shutil.chdir('new_dir'):
    # work with new_dir as current dir
# directory restored when you get here.

Regards,

Vinay Sajip





More information about the Python-ideas mailing list