python - 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
将按预期工作。有没有办法进行优雅的清理?
注意:虽然我的示例非常具体,但我的问题通常是:“我可以进行优雅的清理吗?”
解决方案
停止执行会引发
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 所示。
推荐阅读
- html - 两个 iFrame 之间的 Aria 引用
- regex - 正则表达式匹配精确模式(带或不带撇号的完整单词)而不是单词的部分组成部分
- apache-spark - 如何从独立的 Spark 集群访问 azure 块文件系统 (abfss)
- json - 更改动态嵌套 json 值
- python - 如何为folium中的圆圈添加阴影背景?
- python - 数据帧的 if 语句和调用函数
- javascript - 必须等待第二个文件上传请求才能将第一个数据发送到 AWS S3
- r - 查找具有两个不同类/标签的两列的平均值
- javascript - 如何在队列中设置“状态”
- macos - 命令键作为 iMacros 脚本中的事件 MODIFIERS 值