我尝试在析构函数中删除已创建的目录:
shutil.rmtree("C:\\projects\\project_alpha\\tmp")
它不适用于我的python脚本,但是当我通过python控制台执行此命令时,它可以工作,并且tmp-directory将被删除。
区别在哪里?
答案 0 :(得分:4)
我假设“析构函数”是指__del__
方法。
无法保证为解释器退出时仍然存在的对象调用 del ()方法。
您可能要做的是注册atexit处理程序。
例如在模块级别:
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)
无论解释器如何退出,解释器退出时都会运行使用atexit注册的函数。
当然,你也可以做一些hacky,比如强制垃圾收集器运行(import gc; gc.collect()
,这可能会强制你的 del 方法运行但是我要出去了在这里说一个坏主意。
- )