__del__ 关于退出行为

__del__ on exit behavior

我有一些 test.py 文件:

class A:
    def __init__(self):
        print("A init")

    def __del__(self):
        print("A del")

a = A()

当我 运行 它 10 次 (python3 test.py) 它总是产生下一个输出:

A init
A del

但是如果我在脚本末尾添加 sys.exit 调用:

import sys

class A:
    def __init__(self):
        print("A init")

    def __del__(self):
        print("A del")

a = A()

sys.exit(-1)

10 例中有 5 例(随机)我有

A init

在后半个案例中:

A init
A del    

我在 Windows 7 x64 上使用 Python3.4.3 [MSC v.1600 32 位]。 那么为什么 __del__ 方法不是每次都调用?我是否需要使用其他一些退出方法来传递 return 脚本代码并确保所有析构函数都执行?还有一个相关问题:是否可以在从 OS?

接收到 SIGTERM 或 SIGKILL 时执行析构函数

来自documentation

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

如果要确保 a.__del__ 被调用,则必须显式删除实例:

a = A()
del a   # Assuming this is the final reference to the object