小编Dan*_*Dan的帖子

Python __del__ 未在异常时调用

我试图将一个写得不好的 Python 模块(我无法控制)包装在一个类中。问题是,如果我没有显式调用该模块的 close 函数,那么 python 进程会在退出时挂起,因此我尝试使用具有del方法的类来包装该模块,但是del方法似乎并不适用呼吁例外。

例子:

class Test(object):
    def __init__(self):
        # Initialize the problematic module here
        print "Initializing"

    def __del__(self):
        # Close the problematic module here
        print "Closing"

t = Test()
# This raises an exception
moo()
Run Code Online (Sandbox Code Playgroud)

在这种情况下,不会调用del并且 python 挂起。我需要以某种方式强制Python在对象超出范围时立即调用del (就像C++那样)。请注意,我无法控制有问题的模块(即无法修复首先导致此问题的错误),也无法控制使用包装器类的人(不能强迫他们使用“with”,所以我可以'也不使用退出)。

有没有什么好的方法可以解决这个问题?

谢谢!

python destructor exception

8
推荐指数
1
解决办法
7585
查看次数

标签 统计

destructor ×1

exception ×1

python ×1