Created
December 12, 2013 18:41
-
-
Save john-g-g/7933132 to your computer and use it in GitHub Desktop.
tempfile.mkdtemp relies on user to remove the temp directory it creates, and I know I'm not reliable, so the context manager does it for me.
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
from contextlib import contextmanager | |
import tempfile | |
import shutil | |
import logging | |
log = logging.getLogger(__name__) | |
''' | |
USAGE: | |
with mktempdir() as tempdir: | |
print('Path to temporary directory: %s' % tempdir) | |
print('I'm doing ephemeral things') | |
print('The tempdir has now been removed') | |
''' | |
@contextmanager | |
def mktempdir(): | |
try: | |
tempd = tempfile.mkdtemp() | |
log.debug('Created temp dir: {}'.format(tempd)) | |
yield tempd | |
finally: | |
log.debug('Removing {}'.format(tempd)) | |
shutil.rmtree(tempd, ignore_errors=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment