import contextlib import os import shutil import tempfile @contextlib.contextmanager def temp_dir(): path = tempfile.mkdtemp(dir=os.environ.get('TEMP')) try: yield path finally: shutil.rmtree(path) @contextlib.contextmanager def autoremoved_file(path): try: with open(path, 'w') as handle: yield handle finally: os.unlink(path)