@ wrote... (10 years, 4 months ago)

Python tempdir.mkdtemp() has an annoying feature, it doesn't clean up after itself.

This idea comes from my friend and colleague Mike.

class TempDir(object):
    def __init__(self, suffix='', prefix='tmp', dir=None):
        import tempfile
        self.tdir = tempfile.mkdtemp(suffix, prefix, dir)

    def __enter__(self):
        return self.tdir

    def __exit__(self, type, value, traceback):
            import shutil
            shutil.rmtree( self.tdir )
            import sys
            print >> sys.stderr, "could not delete '%'" % self.tdir

Use like so:

with TempDir() as tdir:
  print "path to tempdir is: %s" % tdir
  os.path.join( tdir, other_file )
  # some other awesome codez go here

# at this point, tdir is now deleted

If that seems magical, read up on context managers

Category: tech, Tags: python
Comments: 0
Click here to add a comment