_contextlib_chdir.py 609 B

12345678910111213141516171819202122
  1. """Backport of Python 3.11's contextlib.chdir."""
  2. import os
  3. from contextlib import AbstractContextManager
  4. class chdir(AbstractContextManager): # type:ignore[type-arg]
  5. """Non thread-safe context manager to change the current working directory."""
  6. def __init__(self, path):
  7. """Initialize the manager."""
  8. self.path = path
  9. self._old_cwd = []
  10. def __enter__(self):
  11. """Enter the context."""
  12. self._old_cwd.append(os.getcwd())
  13. os.chdir(self.path)
  14. def __exit__(self, *excinfo):
  15. """Exit the context."""
  16. os.chdir(self._old_cwd.pop())