Skip to content

Instantly share code, notes, and snippets.

@dbadrian
Created October 24, 2017 10:08
Show Gist options
  • Save dbadrian/ee6a4d76690417754ab06e3f2a01d1b9 to your computer and use it in GitHub Desktop.
Save dbadrian/ee6a4d76690417754ab06e3f2a01d1b9 to your computer and use it in GitHub Desktop.
# https://stackoverflow.com/a/33288373
import contextlib
import os
import shutil
import tempfile
@contextlib.contextmanager
def cd(newdir, cleanup=lambda: True):
prevdir = os.getcwd()
os.chdir(os.path.expanduser(newdir))
try:
yield
finally:
os.chdir(prevdir)
cleanup()
@contextlib.contextmanager
def tempdir():
dirpath = tempfile.mkdtemp()
def cleanup():
shutil.rmtree(dirpath)
with cd(dirpath, cleanup):
yield dirpath
def main():
with tempdir() as dirpath:
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment