Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right way to clean up a temporary folder in Python class

I am creating a class in which I want to generate a temporary workspace of folders that will persist for the life of the object and then be removed. I am using tempfile.mkdtemp() in the def __init__ to create the space, but I have read that I can't rely on __del__ being called.

I am wanting something like this:

class MyClass:   def __init__(self):     self.tempfolder = tempfile.mkdtemp()    def ... #other stuff    def __del__(self):     if os.path.exists(self.tempfolder): shutil.rmtree(self.tempfolder) 

Is there another/better way to handle this clean up? I was reading about with, but it appears to only be helpful within a function.

like image 509
Rob Hunter Avatar asked Nov 14 '12 13:11

Rob Hunter


People also ask

How do I clean out my temporary folder?

Press the Windows Button + R to open the "Run" dialog box. Click "OK." This will open your temp folder. Press Ctrl + A to select all. Press "Delete" on your keyboard and click "Yes" to confirm.

How do I delete temp files in Python?

def removeTempFiles(prefix): files = glob. glob(tempfile. gettempdir() + "/%s*" % prefix) for fn in files: try: os. remove(fn) except OSError: continue # return True if given file exists.

Where is my python TEMP folder?

This name is generally obtained from tempdir environment variable. On Windows platform, it is generally either user/AppData/Local/Temp or windowsdir/temp or systemdrive/temp. On linux it normally is /tmp. This directory is used as default value of dir parameter.


1 Answers

Caveat: you can never guarantee that the temp folder will be deleted, because the user could always hard kill your process and then it can't run anything else.

That said, do

temp_dir = tempfile.mkdtemp() try:     <some code> finally:     shutil.rmtree(temp_dir) 

Since this is a very common operation, Python has a special way to encapsulate "do something, execute code, clean up": a context manager. You can write your own as follows:

@contextlib.contextmanager def make_temp_directory():     temp_dir = tempfile.mkdtemp()     try:         yield temp_dir     finally:         shutil.rmtree(temp_dir) 

and use it as

with make_temp_directory() as temp_dir:     <some code> 

(Note that this uses the @contextlib.contextmanager shortcut to make a context manager. If you want to implement one the original way, you need to make a custom class with __enter__ and __exit__ methods; the __enter__ would create and return the temp directory and the __exit__ delete it.

like image 191
Katriel Avatar answered Oct 05 '22 09:10

Katriel