Created
October 24, 2017 10:08
-
-
Save dbadrian/ee6a4d76690417754ab06e3f2a01d1b9 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
# 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