From bda88892985b015e3ab2c1531ad4656245d4e51e Mon Sep 17 00:00:00 2001 From: Christian Herdtweck Date: Wed, 9 Dec 2015 14:28:07 +0100 Subject: [PATCH] added file_helpers with cd context manager --- file_helpers.py | 31 +++++++++++++++++++++++++++++++ 1 files changed, 31 insertions(+), 0 deletions(-) create mode 100644 file_helpers.py 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) -- 1.7.1