From: Christian Herdtweck Date: Wed, 9 Dec 2015 13:28:07 +0000 (+0100) Subject: added file_helpers with cd context manager X-Git-Tag: v1.2~88 X-Git-Url: http://developer.intra2net.com/git/?a=commitdiff_plain;h=bda88892985b015e3ab2c1531ad4656245d4e51e;p=pyi2ncommon added file_helpers with cd context manager --- diff --git a/file_helpers.py b/file_helpers.py new file mode 100644 index 0000000..20c7f9c --- /dev/null +++ b/file_helpers.py @@ -0,0 +1,31 @@ +""" Helper functions and classes to deal with files and dirs and stuff + +Featuring:: + +* the cd context manager pwd(); with cd(other_dir): pwd(); pwd(); + will print current working dir, then other_dir, then first dir again + +.. todo:: create unittest + +.. codeauthor:: Christian Herdtweck, christian.herdtweck@intra2net.com +""" + +import contextlib +import os + + +@contextlib.contextmanager +def cd(path): + """A context manager which changes the working directory to the given + path, and then changes it back to its previous value on exit. + + Taken from comment for python recipe by Greg Warner at + http://code.activestate.com/recipes/576620-changedirectory-context-manager/ + (MIT license) + """ + prev_cwd = os.getcwd() + os.chdir(path) + try: + yield + finally: + os.chdir(prev_cwd)