_tempfs.py 924 B

12345678910111213141516171819202122232425262728293031323334
  1. from __future__ import annotations
  2. import shutil
  3. import tempfile
  4. from ._errors import OperationFailed
  5. from ._osfs import OSFS
  6. class TempFS(OSFS):
  7. def __init__(self, auto_clean: bool = True, ignore_clean_errors: bool = True):
  8. self.auto_clean = auto_clean
  9. self.ignore_clean_errors = ignore_clean_errors
  10. self._temp_dir = tempfile.mkdtemp("__temp_fs__")
  11. self._cleaned = False
  12. super().__init__(self._temp_dir)
  13. def close(self):
  14. if self.auto_clean:
  15. self.clean()
  16. super().close()
  17. def clean(self):
  18. if self._cleaned:
  19. return
  20. try:
  21. shutil.rmtree(self._temp_dir)
  22. except Exception as e:
  23. if not self.ignore_clean_errors:
  24. raise OperationFailed(
  25. f"failed to remove temporary directory: {self._temp_dir!r}"
  26. ) from e
  27. self._cleaned = True