python - 从定时器中捕获异常

标签 python exception timer watchdog

我正在尝试创建一个看门狗类,它将在指定时间后抛出异常:

from threading import Timer
from time import sleep

class watchdog():
  def _timeout(self):
    #raise self
    raise TypeError

  def __init__(self):
    self.t = Timer(1, self._timeout)

  def start(self):
    self.t.start()

try:
  w = watchdog()
  w.start()
  sleep(2)
except TypeError, e:
  print "Exception caught"
else:
  print "Of course I didn't catch the exception"

此异常未被捕获,因为异常是从完全不同的上下文中抛出的,因此我们将看到最后一条消息。

我的问题是,如何修改代码,才能捕获异常?

最佳答案

正如您所建议的那样,这是不可能的,而且 there is no api for abruptly stopping a thread ,这就排除了其他可能的解决方案。

我相信您最好的解决方案是让看门狗设置一个标志,并让测试在某些点读取它。同样,您的测试可以不时检查持续时间。

请注意,如果“标志”的设置方式会导致主线程引发异常(例如,从对象中删除属性),它将同样有效。

如果您的应用程序可行,另一种可能性是使用多处理而不是多线程。

关于python - 从定时器中捕获异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30391353/

相关文章:

Python-如何拆分字符串列表以按原始顺序获得唯一的拆分

python - 具有 "dynamic"模式的 flask-sqlalchemy 跨数据库

Android:无法启动 Activity 。 ClassCastException:android.Widget.Button

python - 如何在数学函数中使用获取下一个乘法数字

python - 使用 Python3 通过 python-dbus 在 Linux 上显示屏幕保护程序状态

powershell - 异常在 "ValidateCredentials" "The server cannot handle directory requests."

c++ - 处理 CTOR 抛出的异常?

c++ - QTimer 自行停止和启动

python - 在 Python 中获取计时器刻度

java - 倒数计时器在手机关闭或应用程序被杀死时仍然运行