tempdir.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. """ This module contains classes - NamedFileInTemporaryDirectory, TemporaryWorkingDirectory.
  2. These classes add extra features such as creating a named file in temporary directory and
  3. creating a context manager for the working directory which is also temporary.
  4. """
  5. import os as _os
  6. from pathlib import Path
  7. from tempfile import TemporaryDirectory
  8. class NamedFileInTemporaryDirectory(object):
  9. def __init__(self, filename, mode="w+b", bufsize=-1, add_to_syspath=False, **kwds):
  10. """
  11. Open a file named `filename` in a temporary directory.
  12. This context manager is preferred over `NamedTemporaryFile` in
  13. stdlib `tempfile` when one needs to reopen the file.
  14. Arguments `mode` and `bufsize` are passed to `open`.
  15. Rest of the arguments are passed to `TemporaryDirectory`.
  16. """
  17. self._tmpdir = TemporaryDirectory(**kwds)
  18. path = Path(self._tmpdir.name) / filename
  19. encoding = None if "b" in mode else "utf-8"
  20. self.file = open(path, mode, bufsize, encoding=encoding)
  21. def cleanup(self):
  22. self.file.close()
  23. self._tmpdir.cleanup()
  24. __del__ = cleanup
  25. def __enter__(self):
  26. return self.file
  27. def __exit__(self, type, value, traceback):
  28. self.cleanup()
  29. class TemporaryWorkingDirectory(TemporaryDirectory):
  30. """
  31. Creates a temporary directory and sets the cwd to that directory.
  32. Automatically reverts to previous cwd upon cleanup.
  33. Usage example:
  34. with TemporaryWorkingDirectory() as tmpdir:
  35. ...
  36. """
  37. def __enter__(self):
  38. self.old_wd = Path.cwd()
  39. _os.chdir(self.name)
  40. return super(TemporaryWorkingDirectory, self).__enter__()
  41. def __exit__(self, exc, value, tb):
  42. _os.chdir(self.old_wd)
  43. return super(TemporaryWorkingDirectory, self).__exit__(exc, value, tb)