Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class TemporaryDirectory(object):
- """
- Produces a temporary directory on the system using tempfile.mkdtemp() under the hood.
- Exposes a path attribute that will represent the path of the directory
- until the instance has deleted the temporary directory.
- TemporaryDirectory can be used as a context manager.
- """
- def __init__(self, suffix=None, prefix=None, _dir=None):
- super(self.__class__, self).__init__()
- kwargs = {}
- if suffix is not None:
- kwargs["suffix"] = suffix
- if prefix is not None:
- kwargs["prefix"] = prefix
- if dir is not None:
- kwargs["dir"] = _dir
- self.path = tempfile.mkdtemp(**kwargs)
- self.deleted = False
- def __enter__(self):
- return self.path
- def __exit__(self, *_):
- self.delete()
- def delete(self):
- if self.deleted is True:
- raise Exception("The temporary directory has already been deleted via an instance method.")
- if self.path is not None:
- try:
- shutil.rmtree(self.path)
- self.path = None
- self.deleted = True
- return True
- except Exception as e:
- logger.exception(e)
- raise
- else:
- raise Exception("The TemporaryDirectory is not aware of its path.")
Add Comment
Please, Sign In to add comment