added file_helpers with cd context manager
authorChristian Herdtweck <christian.herdtweck@intra2net.com>
Wed, 9 Dec 2015 13:28:07 +0000 (14:28 +0100)
committerChristian Herdtweck <christian.herdtweck@intra2net.com>
Wed, 9 Dec 2015 13:28:07 +0000 (14:28 +0100)
file_helpers.py [new file with mode: 0644]

diff --git a/file_helpers.py b/file_helpers.py
new file mode 100644 (file)
index 0000000..20c7f9c
--- /dev/null
@@ -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)