Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(14554)

Unified Diff: Lib/tempfile.py

Issue 5178: Add context manager for temporary directory
Patch Set: Created 8 years, 11 months ago
Use n/p to move between diff chunks; N/P to move between comments. Please Sign in to add in-line comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « Doc/library/tempfile.rst ('k') | Lib/test/test_bsddb185.py » ('j') | no next file with comments »
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: Lib/tempfile.py
===================================================================
--- Lib/tempfile.py (revision 69412)
+++ Lib/tempfile.py (working copy)
@@ -601,3 +601,59 @@
def xreadlines(self, *args):
return self._file.xreadlines(*args)
+
+
+class TemporaryDirectory(object):
+ """Create and return a temporary directory. This has the same
+ behavior as mkdtemp but can be used as a context manager. For
+ example:
+
+ with TemporaryDirectory() as tmpdir:
+ ...
+
+ Upon exiting the context, the directory and everthing contained
+ in it are removed.
+ """
+
+ def __init__(self, suffix="", prefix=template, dir=None):
+ self.name = mkdtemp(suffix, prefix, dir)
+ self._closed = False
+
+ def __enter__(self):
+ return self.name
+
+ def cleanup(self):
+ if not self._closed:
+ self._rmtree(self.name)
+ self._closed = True
+
+ def __exit__(self, exc, value, tb):
+ self.cleanup()
+
+ _listdir = _os.listdir
+ _path_join = _os.path.join
+ _isdir = _os.path.isdir
+ _remove = _os.remove
+ _rmdir = _os.rmdir
+ _os_error = _os.error
+
+ def _rmtree(self, path):
+ # Essentially a stripped down version of shutil.rmtree. We can't
+ # use globals because they may be None'ed out at shutdown.
+ for name in self._listdir(path):
+ fullname = self._path_join(path, name)
+ try:
+ isdir = self._isdir(fullname)
+ except self._os_error:
+ isdir = False
+ if isdir:
+ self._rmtree(fullname)
+ else:
+ try:
+ self._remove(fullname)
+ except self._os_error:
+ pass
+ try:
+ self._rmdir(path)
+ except self._os_error:
+ pass
« no previous file with comments | « Doc/library/tempfile.rst ('k') | Lib/test/test_bsddb185.py » ('j') | no next file with comments »

RSS Feeds Recent Issues | This issue
This is Rietveld 894c83f36cb7+