shazow / unstdlib.py

Unstandard Python library of useful and highly-reusable functions.

Home Page:http://pypi.python.org/pypi/unstdlib

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Create mkdtemp context manager

wolever opened this issue · comments

Something along the lines of:

class mkdtemp(object):
    def __init__(self, *args, **kwargs):
        self.should_chdir = kwargs.pop("chdir")
        self.original_dir = None
        self.dirname = tempfile.mkdtemp(*args, **kwargs)

    def __enter__(self):
        if self.should_chdir:
            self.original_dir = os.getcwd()
            os.chdir(self.dirname)
        return self.dirname

    def __exit__(self, *exc):
        if self.original_dir:
            os.chdir(self.original_dir)
        shutil.rmtree(self.dirname)

with mkdtemp("foo", chdir=True) as dirname:
    print "I'm in", dirname

I wondered about returning self from __enter__: it might be better to return self.dirname, really.

D'oh! Yes, that does make more sense.

I love that this has been more than a year, but I'm still +1.