I am writing a library that creates temporary files and calls a series
of external programs to process these files. Sometimes these external
programs create files in the same directory as the input files, so to
make sure they are all deleted, one must create them in a temporary
directory, then delete it.
I've written a NamedTemporaryD ir class which is derived somewhat from
tempfile.NamedT emporaryFile in the standard library. Right now I am
using NamedTemporaryF ile to create individual files, but since I am
putting them in a directory that will be deleted anyway, I'm wondering
if I can simplify things (and not have to keep track of all fo the
NamedTemporaryF ile instances) by using tempfile.mkstem p() specifying my
temporary directory, and relying on the directory deletion when exiting
its with block.
Is there any reason I should keep track of each temporary files myself
instead of deleting the whole directory?
I am using Linux, but I would also be interested in cross-platform
considerations.
Also, the code is below. Is this worth submitting as a patch?
# NamedTemporaryF ile is based somewhat on Python 2.5.2
# tempfile._Tempo raryFileWrapper
#
# Original Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006 Python
# Software Foundation; All Rights Reserved
#
# License at http://www.python.org/download/releases/2.5.2/license/
from tempfile import mkdtemp
class NamedTemporaryD ir(object):
def __init__(self, *args, **kwargs):
self.name = mkdtemp(*args, **kwargs)
self.close_call ed = False
def __enter__(self) :
return self
unlink = os.unlink
def close(self):
if not self.close_call ed:
self.close_call ed = True
self.unlink(sel f.name)
def __del__(self):
self.close()
def __exit__(self, exc, value, tb):
result = self.file.__exi t__(exc, value, tb)
self.close()
return result