Bring back cd context manager
authorChristian Herdtweck <christian.herdtweck@intra2net.com>
Mon, 29 Oct 2018 08:41:37 +0000 (09:41 +0100)
committerChristian Herdtweck <christian.herdtweck@intra2net.com>
Mon, 5 Nov 2018 11:21:54 +0000 (12:21 +0100)
This has been in pyi2ncommon before but was removed since it was only used
in one place (which exists no more). Now needed it again, so bring it back.

src/sysmisc.py

index d7fe611..6898f31 100644 (file)
@@ -73,6 +73,9 @@ cheat_reboot
 cmd_block_till
     Run a command and wait until a condition evaluates to True.
 
+cd
+    A context manager that temporarily changes the current working directory
+
 The logging functions either use the format capability or play
 the simple role of providing shorter names.
 
@@ -92,6 +95,7 @@ import stat
 import time
 import types
 import uuid
+from contextlib import contextmanager
 import logging
 llog = logging.getLogger('pyi2ncommon.sysmisc')
 
@@ -103,6 +107,26 @@ __all__ = ("inf", "run_cmd_with_pipe", "get_mountpoints_by_type", "read_linewise
 # HELPERS
 ###############################################################################
 
+@contextmanager
+def cd(path):
+    """
+    A context manager which changes the working directory.
+
+    Changes current 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)
+    """
+    orig_wd = os.getcwd()
+    os.chdir(path)
+    try:
+        yield
+    finally:
+        os.chdir(orig_wd)
+
+
 def run_cmd_with_pipe(argv, inp=None):
     """
     Read from a process pipe.