异常时未调用Python

2024-04-18 06:00:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图在一个类中包装一个写得不好的Python模块(我无法控制)。问题是,如果我没有显式地调用该模块的close函数,那么python进程将挂起在exit上,因此我尝试用一个具有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()

在这种情况下,del不被调用,python挂起。当对象超出范围(如C++)时,我需要某种方式强制Python立即调用<强> del <强>。 请注意,我无法控制有问题的模块(即无法首先修复导致此问题的bug),也无法控制使用包装类的任何人(不能强制他们使用“with”,因此我也不能使用exit)。在

有什么好办法解决这个问题吗?在

谢谢!在


Tags: 模块the方法函数testselfclosehere
3条回答

一个可能的解决方案是使用sys.excepthook,这允许您将自定义登录引入全局异常处理程序。您可以在那里添加一些代码来关闭模块的剩余部分。在

如果您希望在异常时释放一些资源,可以考虑使用优enter_优+\uuu exit_uu范式。在

class Test(object):
    def __enter__(self):
        pass

    def __exit__(self):
        pass  # Release your resources here

with Test() as t:
    moo()

当执行进入“with”块时,将调用“t”的方法enter_u2;(),然后由于正常流或异常而离开该块,则调用“t”的方法exit_uux()。在

相关问题 更多 >