From: Christian Herdtweck Date: Mon, 29 Oct 2018 08:41:37 +0000 (+0100) Subject: Bring back cd context manager X-Git-Tag: v1.4~17^2~5 X-Git-Url: http://developer.intra2net.com/git/?a=commitdiff_plain;h=872eaff18389066a87bdd6b860dd11a2c3f89b0a;p=pyi2ncommon Bring back cd context manager 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. --- diff --git a/src/sysmisc.py b/src/sysmisc.py index d7fe611..6898f31 100644 --- a/src/sysmisc.py +++ b/src/sysmisc.py @@ -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.