Return to Snippet

Revision: 49131
at July 16, 2011 18:31 by ches


Updated Code
from __future__ import with_statement # only for python 2.5
import contextlib
import os

@contextlib.contextmanager
def chdir(dirname=None):
    curdir = os.getcwd()
    try:
        if dirname is not None:
        os.chdir(dirname)
        yield
    finally:
        os.chdir(curdir)

Revision: 49130
at July 16, 2011 18:30 by ches


Updated Code
from __future__ import with_statement # only for python 2.5
import contextlib
import os

@contextlib.contextmanager
def chdir(dirname=None):
curdir = os.getcwd()
try:
    if dirname is not None:
    os.chdir(dirname)
    yield
finally:
    os.chdir(curdir)

Revision: 49129
at July 16, 2011 18:28 by ches


Initial Code
from __future__ import with_statement # only for python 2.5 
import contextlib
import os 

@contextlib.contextmanager
def chdir(dirname=None):
curdir = os.getcwd()
try:
if dirname is not None:
os.chdir(dirname)
yield
finally:
os.chdir(curdir)

Initial URL
http://www.astropython.org/snippet/2009/10/chdir-context-manager

Initial Description
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.

Initial Title
chdir context manager

Initial Tags
python

Initial Language
Python