# HG changeset patch # User Jeff Hammel # Date 1512955170 28800 # Node ID 9b1bb9eee962db4cf93045aceae45f5f7c84cc30 # Parent 0d1b8bb1d97bb795d4774ed0a65e6319457c95d1 misc functions related to filesystem paths diff -r 0d1b8bb1d97b -r 9b1bb9eee962 lemuriformes/path.py --- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/lemuriformes/path.py Sun Dec 10 17:19:30 2017 -0800 @@ -0,0 +1,35 @@ +""" +functions related to paths +""" + +import shutil +import tempfile + + +def ensure_dir(path): + """ensures `path` is a directory""" + + if os.path.exists(path): + assert os.path.isdir(path) + else: + os.makedirs(path) + return path + + +class TempDir(object): + """temporary directory context manager""" + # For inspiration see + # https://stackoverflow.com/questions/19296146/tempfile-temporarydirectory-context-manager-in-python-2-7 + + def __init__(self): + self.tmpdir = None + + def __enter__(self): + self.tmpdir = tempfile.mkdtemp() + return self.tmpdir + + def __exit__(self, *args): + if not self.tmpdir: + return + shutil.rmtree(self.tmpdir, ignore_errors=True) + self.tmpdir = None