首页 > 解决方案 > Python - 如果用户试图中途停止执行,有没有办法让函数优雅地清理?

问题描述

说我有一个像

class Thing():

    def __init__(self):
        self.some_state = False

    def do_stuff(self):
        self.some_state = True
        # do stuff which may take some time - and user may quit here
        self.some_state = False

    def do_other_stuff(self):
        # do stuff which depends on `some_state` being False

我想确保如果用户通过运行在笔记本中执行此操作:

thing = Thing()
thing.do_stuff()

然后在运行时按“停止执行”,some_state切换回False. 这种方式do_other_stuff将按预期工作。有没有办法进行优雅的清理?

注意:虽然我的示例非常具体,但我的问题通常是:“我可以进行优雅的清理吗?”

标签: python

解决方案


停止执行会引发 KeyboardInterrupt异常,因此您需要处理该异常some_state但实际上,如果代码因其他异常而退出,您可能需要重置。即使您没有明确提出异常,它们也可能由于代码中的错误或内存不足而发生。所以在一个finally子句中进行清理。

    def do_stuff(self):
        self.some_state = True
        try:
            # do stuff which may take some time - and user may quit here
        finally:
            self.some_state = False

如果许多方法需要相同的清理,您可以使用装饰器,如Tgsmith61591 所示


推荐阅读