Guest User

Untitled

a guest
Jan 19th, 2019
86
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.35 KB | None | 0 0
  1. class TemporaryDirectory(object):
  2. """
  3. Produces a temporary directory on the system using tempfile.mkdtemp() under the hood.
  4.  
  5. Exposes a path attribute that will represent the path of the directory
  6. until the instance has deleted the temporary directory.
  7.  
  8. TemporaryDirectory can be used as a context manager.
  9.  
  10. """
  11.  
  12. def __init__(self, suffix=None, prefix=None, _dir=None):
  13. super(self.__class__, self).__init__()
  14.  
  15. kwargs = {}
  16.  
  17. if suffix is not None:
  18. kwargs["suffix"] = suffix
  19.  
  20. if prefix is not None:
  21. kwargs["prefix"] = prefix
  22.  
  23. if dir is not None:
  24. kwargs["dir"] = _dir
  25.  
  26. self.path = tempfile.mkdtemp(**kwargs)
  27. self.deleted = False
  28.  
  29. def __enter__(self):
  30. return self.path
  31.  
  32. def __exit__(self, *_):
  33. self.delete()
  34.  
  35. def delete(self):
  36. if self.deleted is True:
  37. raise Exception("The temporary directory has already been deleted via an instance method.")
  38.  
  39. if self.path is not None:
  40. try:
  41. shutil.rmtree(self.path)
  42.  
  43. self.path = None
  44. self.deleted = True
  45.  
  46. return True
  47. except Exception as e:
  48. logger.exception(e)
  49.  
  50. raise
  51. else:
  52. raise Exception("The TemporaryDirectory is not aware of its path.")
Add Comment
Please, Sign In to add comment