| 1 |
""" |
| 2 |
https://github.com/pjdelport/backports.tempfile/blob/master/src/backports/tempfile.py |
| 3 |
Partial backport of Python 3.5's tempfile module: |
| 4 |
TemporaryDirectory |
| 5 |
Backport modifications are marked with marked with "XXX backport". |
| 6 |
""" |
| 7 |
from __future__ import absolute_import |
| 8 |
|
| 9 |
import sys |
| 10 |
import warnings as _warnings |
| 11 |
from shutil import rmtree as _rmtree |
| 12 |
|
| 13 |
from py2backports.weakref import finalize |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
if sys.version_info < (3, 5): |
| 19 |
from tempfile import mkdtemp as old_mkdtemp |
| 20 |
|
| 21 |
def mkdtemp(suffix=None, prefix=None, dir=None): |
| 22 |
""" |
| 23 |
Wrap `tempfile.mkdtemp()` to make the suffix and prefix optional (like Python 3.5). |
| 24 |
""" |
| 25 |
kwargs = {k: v for (k, v) in |
| 26 |
dict(suffix=suffix, prefix=prefix, dir=dir).items() |
| 27 |
if v is not None} |
| 28 |
return old_mkdtemp(**kwargs) |
| 29 |
|
| 30 |
else: |
| 31 |
from tempfile import mkdtemp |
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
_ResourceWarning = RuntimeWarning if sys.version_info < (3, 2) else ResourceWarning |
| 37 |
|
| 38 |
|
| 39 |
class TemporaryDirectory(object): |
| 40 |
"""Create and return a temporary directory. This has the same |
| 41 |
behavior as mkdtemp but can be used as a context manager. For |
| 42 |
example: |
| 43 |
with TemporaryDirectory() as tmpdir: |
| 44 |
... |
| 45 |
Upon exiting the context, the directory and everything contained |
| 46 |
in it are removed. |
| 47 |
""" |
| 48 |
|
| 49 |
def __init__(self, suffix=None, prefix=None, dir=None): |
| 50 |
self.name = mkdtemp(suffix, prefix, dir) |
| 51 |
self._finalizer = finalize( |
| 52 |
self, self._cleanup, self.name, |
| 53 |
warn_message="Implicitly cleaning up {!r}".format(self)) |
| 54 |
|
| 55 |
@classmethod |
| 56 |
def _cleanup(cls, name, warn_message): |
| 57 |
_rmtree(name) |
| 58 |
_warnings.warn(warn_message, _ResourceWarning) |
| 59 |
|
| 60 |
|
| 61 |
def __repr__(self): |
| 62 |
return "<{} {!r}>".format(self.__class__.__name__, self.name) |
| 63 |
|
| 64 |
def __enter__(self): |
| 65 |
return self.name |
| 66 |
|
| 67 |
def __exit__(self, exc, value, tb): |
| 68 |
self.cleanup() |
| 69 |
|
| 70 |
def cleanup(self): |
| 71 |
if self._finalizer.detach(): |
| 72 |
_rmtree(self.name) |