Created
August 26, 2014 14:40
-
-
Save cpelley/10e2eeaf60dacc7956bb to your computer and use it in GitHub Desktop.
Support for temporary directories in python2.7 as context managers (already available in python3.2+)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import shutil | |
import tempfile | |
class TemporaryDirectory(object): | |
""" | |
Context manager for tempfile.mkdtemp(). | |
This class is available in python +v3.2. | |
""" | |
def __enter__(self): | |
self.dir_name = tempfile.mkdtemp() | |
return self.dir_name | |
def __exit__(self, exc_type, exc_value, traceback): | |
shutil.rmtree(self.dir_name) | |
TemporaryDirectory = getattr(tempfile, 'TemporaryDirectory', | |
TemporaryDirectory) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment