view lemuriformes/path.py @ 18:56596902e9ae default tip

add some setup + tests
author Jeff Hammel <k0scist@gmail.com>
date Sun, 10 Dec 2017 17:57:03 -0800
parents 9b1bb9eee962
children
line wrap: on
line source

"""
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