diff options
author | Filipe Laíns <lains@riseup.net> | 2021-10-19 22:19:27 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-10-19 22:19:27 (GMT) |
commit | 3592980f9122ab0d9ed93711347742d110b749c2 (patch) | |
tree | e1e3a4894a60187a5152c2a8c3ae648987f5f75b /Lib/contextlib.py | |
parent | ad6d162e518963711d24c80f1b7d6079bd437584 (diff) | |
download | cpython-3592980f9122ab0d9ed93711347742d110b749c2.zip cpython-3592980f9122ab0d9ed93711347742d110b749c2.tar.gz cpython-3592980f9122ab0d9ed93711347742d110b749c2.tar.bz2 |
bpo-25625: add contextlib.chdir (GH-28271)
Added non parallel-safe :func:`~contextlib.chdir` context manager to change
the current working directory and then restore it on exit. Simple wrapper
around :func:`~os.chdir`.
Signed-off-by: Filipe Laíns <lains@riseup.net>
Co-authored-by: Łukasz Langa <lukasz@langa.pl>
Diffstat (limited to 'Lib/contextlib.py')
-rw-r--r-- | Lib/contextlib.py | 19 |
1 files changed, 18 insertions, 1 deletions
diff --git a/Lib/contextlib.py b/Lib/contextlib.py index d90ca5d..ee72258 100644 --- a/Lib/contextlib.py +++ b/Lib/contextlib.py @@ -1,5 +1,6 @@ """Utilities for with-statement contexts. See PEP 343.""" import abc +import os import sys import _collections_abc from collections import deque @@ -9,7 +10,8 @@ from types import MethodType, GenericAlias __all__ = ["asynccontextmanager", "contextmanager", "closing", "nullcontext", "AbstractContextManager", "AbstractAsyncContextManager", "AsyncExitStack", "ContextDecorator", "ExitStack", - "redirect_stdout", "redirect_stderr", "suppress", "aclosing"] + "redirect_stdout", "redirect_stderr", "suppress", "aclosing", + "chdir"] class AbstractContextManager(abc.ABC): @@ -762,3 +764,18 @@ class nullcontext(AbstractContextManager, AbstractAsyncContextManager): async def __aexit__(self, *excinfo): pass + + +class chdir(AbstractContextManager): + """Non thread-safe context manager to change the current working directory.""" + + def __init__(self, path): + self.path = path + self._old_cwd = [] + + def __enter__(self): + self._old_cwd.append(os.getcwd()) + os.chdir(self.path) + + def __exit__(self, *excinfo): + os.chdir(self._old_cwd.pop()) |