Skip to content

Instantly share code, notes, and snippets.

@cpelley
Created August 26, 2014 14:40
Show Gist options
  • Save cpelley/10e2eeaf60dacc7956bb to your computer and use it in GitHub Desktop.
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+)
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