Skip to content

Instantly share code, notes, and snippets.

@john-g-g
Created December 12, 2013 18:41
Show Gist options
  • Save john-g-g/7933132 to your computer and use it in GitHub Desktop.
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.
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