Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you manage a temporary directory such that it is guaranteed to be deleted on program close?

I'm working with a temporary directory and I want to make sure that it gets deleted on program close (regardless of whether the program was successful). I'm using tempfile.mkdtempto create the directory and putting the string that's created into a subclass of str that deletes the directory on its __del__ command:

import shutil
import tempfile

class TempDir(str):
    """ container for temporary directory. 
    Deletes directory when garbage collected/zero references """
    def __del__(self):
        shutil.rmtree(self.__str__(), onerror=my_error_fn)

dbdir = TempDir(tempfile.mkdtemp())

Here's what I'm not sure about: if the program closes or a KeyboardInterrupt happens, will Python automatically delete/garbage collect all the variables? If not, how could I make sure that the directory gets deleted?

Related info about creating destructor methods in Python. Seems like so long as the TempDir object doesn't reference anything else, using __del__ to destruct it should be fine.

like image 272
Jeff Tratner Avatar asked Jun 10 '12 00:06

Jeff Tratner


1 Answers

I wouldn't use a __del__ method, the semantics are unreliable, and could interfere with garbage collection. Use a context manager: define a __enter__ and __exit__ method, and put your use of the object in a with statement. It's clear, it's explicit, and it will work without worry.

Or, another way to make a context manager:

@contextlib.contextmanager
def tempdir(prefix='tmp'):
    """A context manager for creating and then deleting a temporary directory."""
    tmpdir = tempfile.mkdtemp(prefix=prefix)
    try:
        yield tmpdir
    finally:
        shutil.rmtree(tmpdir)
like image 122
Ned Batchelder Avatar answered Sep 22 '22 17:09

Ned Batchelder