
On Tue, 2021-09-14 at 21:43 +0200, Marc-Andre Lemburg wrote:
Hello all,
I sometimes write Python scripts which need to work in specific work directories.
When putting such code into functions, the outer function typically does not expect the current work dir (CWD) to be changed, so wrap the code which need the (possibly) modified CWD using a simply context manager along the lines of:
class workdir: def __init__(self, dir): self.dir = dir def __enter__(self): self.curdir = os.getcwd() os.chdir(self.dir) def __exit__(self, *exc): os.chdir(self.curdir) return False
Would there be interest in adding something like this to the os module as os.workdir() ?
Example:
def backup_home_dir(account): with os.workdir(os.path.join('/home', account)): # Create a backup of the account dir, rooted at the account's # home dir restic.backup(repo, '.')
Notes: - The context manager is not thread safe. There's no thread safe model for the current work dir. OTOH, scripts usually don't use threads, so not a big deal. - The context manager could be made more elaborate, e.g. adding optional logging for debugging purposes. - The same could be added to pathlib's objects as .workdir() method returning a context manager.
Thoughts ?
Thanks,
bpo: https://bugs.python.org/issue25625 PR: https://github.com/python/cpython/pull/28271 Filipe Laíns