##// END OF EJS Templates
Add context manager for temporary directories from Python 3.2...
Fernando Perez -
Show More
@@ -0,0 +1,76
1 """TemporaryDirectory class, copied from Python 3.2.
2
3 This is copied from the stdlib and will be standard in Python 3.2 and onwards.
4 """
5
6 # This code should only be used in Python versions < 3.2, since after that we
7 # can rely on the stdlib itself.
8 try:
9 from tempfile import TemporaryDirectory
10
11 except ImportError:
12
13 import os as _os
14 from tempfile import mkdtemp, template
15
16 class TemporaryDirectory(object):
17 """Create and return a temporary directory. This has the same
18 behavior as mkdtemp but can be used as a context manager. For
19 example:
20
21 with TemporaryDirectory() as tmpdir:
22 ...
23
24 Upon exiting the context, the directory and everthing contained
25 in it are removed.
26 """
27
28 def __init__(self, suffix="", prefix=template, dir=None):
29 self.name = mkdtemp(suffix, prefix, dir)
30 self._closed = False
31
32 def __enter__(self):
33 return self.name
34
35 def cleanup(self):
36 if not self._closed:
37 self._rmtree(self.name)
38 self._closed = True
39
40 def __exit__(self, exc, value, tb):
41 self.cleanup()
42
43 __del__ = cleanup
44
45
46 # XXX (ncoghlan): The following code attempts to make
47 # this class tolerant of the module nulling out process
48 # that happens during CPython interpreter shutdown
49 # Alas, it doesn't actually manage it. See issue #10188
50 _listdir = staticmethod(_os.listdir)
51 _path_join = staticmethod(_os.path.join)
52 _isdir = staticmethod(_os.path.isdir)
53 _remove = staticmethod(_os.remove)
54 _rmdir = staticmethod(_os.rmdir)
55 _os_error = _os.error
56
57 def _rmtree(self, path):
58 # Essentially a stripped down version of shutil.rmtree. We can't
59 # use globals because they may be None'ed out at shutdown.
60 for name in self._listdir(path):
61 fullname = self._path_join(path, name)
62 try:
63 isdir = self._isdir(fullname)
64 except self._os_error:
65 isdir = False
66 if isdir:
67 self._rmtree(fullname)
68 else:
69 try:
70 self._remove(fullname)
71 except self._os_error:
72 pass
73 try:
74 self._rmdir(path)
75 except self._os_error:
76 pass
General Comments 0
You need to be logged in to leave comments. Login now