python - 如何在 Python 中停止函数中间运行
问题描述
我有很多次不得不在运行过程中停止一个函数,而无法访问它,或者它有数百行代码,如果对每一行进行 if-check 是不可行的,或者它以某种方式被击中。那是由代码本身触发的。
我曾经sys.settrace
完成任务,就像在这个 MWE 中一样:
from threading import Event, Thread
import sys
import time
_stop = Event()
def _globaltrace(frame, event, arg):
"""The global trace call handler."""
if event == 'call':
return _localtrace
else:
return None
def _localtrace(frame, event, arg):
"""The local trace call handler."""
global _stop
if _stop.is_set():
if event == 'line':
raise Exception()
return _localtrace
if __name__ == "__main__":
def long_function():
# The Function that need to be terminated before it ends.
# That we _CAN'T_ change anything in.
print("Long Function Started.")
while True:
time.sleep(1)
def simulate_external_input_callback():
global _stop
time.sleep(5)
print("Kill signal received.")
_stop.set()
sys.settrace(_globaltrace)
th = Thread(target=simulate_external_input_callback)
th.start()
try:
long_function()
except Exception:
print("Long Function Killed.")
# Try to do some cleanup.
else:
print("Long function ended normally.")
print("The program continues, like nothing happened.")
th.join() # Just here for clean up.
然后有一个东西来设置事件:_stop.set()
在需要时,通过回调或计时器,并有一个 try-except 来捕获它。
但这是一个讨厌的 hack,正如其他人所说,这通常是不必要的。我相信他们,我不能只是想另一种解决方案。
所以我希望有人知道“正确”的解决方案,在没有使用的地方sys.settrace
,终端long_function
。
解决方案
推荐阅读
- php - 仅包含 php 和 mysql 的依赖下拉列表
- python - 结合 iloc 和 loc
- javascript - 如何在 React (GET/PUT/POST) 中将 curl 命令转换为 Axios 调用
- sql - 在 MS-Access 中加入两个使用聚合的查询
- javascript - TypeError:无法读取未定义的属性“地图” - 如何访问本地 json API 中的数组
- datetime - 我如何在chartjs图表上显示我的自定义(日-月-年时:分:秒)时间格式?
- openshift - 如何在开始构建之前授予容器 root 权限(服务帐户)
- c - 包含动态分配数组的结构中的段错误
- mongodb - 通过stitch aws服务上传图片到s3失败
- javascript - 带有 django 后端的 DataTable 编辑器,用于内联编辑