Вопрос

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?

Это было полезно?

Решение

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.

;-)

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top