Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

shutil.rmtree(...) does not work in my script

Tags:

python

shutil

I try to delete a created directory in my destructor:

shutil.rmtree("C:\\projects\\project_alpha\\tmp")

It does not work with my python script but when I execute this command via python console it works and the tmp-directory will deleted.

Where is the difference?

like image 681
bob morane Avatar asked Feb 15 '26 23:02

bob morane


1 Answers

I assume by "destructor" you mean the __del__ method.

From the docs on del

It is not guaranteed that del() methods are called for objects that still exist when the interpreter exits.

What you might want to do is register an atexit handler.

For example at module level:

import atexit

def cleanup_directories():
    directories = ["C:\\projects\\project_alpha\\tmp",]
    for path in directories:
        if os.path.exists(path) and os.path.isdir(path):
            shutil.rmtree(path)

atexit.register(cleanup_directories)

Functions registered with atexit will be run when the interpreter exits regardless of how the interpreter exits.

Of course, you could also do something hacky like force the garbage collector to run (import gc; gc.collect(), which may force your del method to run but I'm going to go out on a limb here and say that's a bad idea.

;-)

like image 178
stderr Avatar answered Feb 18 '26 13:02

stderr