Python - 如果用户试图在中途停止执行,有没有办法优雅地清理函数?

标签 python

关闭。这个问题需要details or clarity .它目前不接受答案。












想改善这个问题吗?通过 editing this post 添加详细信息并澄清问题.

去年关闭。




Improve this question




说我有一个类

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将按预期工作。有没有办法做一些优雅的清理?
注意:虽然我的例子很具体,但我的问题通常是:“我可以进行优雅的清理吗?”

最佳答案

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

    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
如果许多方法需要相同的清理,您可以使用 decoratorillustrated by Tgsmith61591 .

关于Python - 如果用户试图在中途停止执行,有没有办法优雅地清理函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63954327/

相关文章:

python - 将两个字典的信息翻译成字典列表

python - Django : Manipulate Data in a generic. ListView

使用 pyodbc 的 python 类。多行错误

python - multiprocessing.Process(使用 spawn 方法): which objects are inherited?

python - 来自 Mechanize 缓存的浏览器实例是否?

jquery - 添加额外字段以查找该对象是否与另一个对象相关

python - 从包含特定字符的列表中删除元素

python - Numpy 将函数应用于选定的矩阵索引

python - 使用 BeautifulSoup 在第一个子标签之前提取文本

python - 写入我的临时文件的权限被拒绝