从计时器捕获异常

时间:2015-05-22 08:00:03

标签: 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"

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

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

1 个答案:

答案 0 :(得分:2)

This is not possible, as you suggested, and there is no api for abruptly stopping a thread, either, which rules out other potential solutions.

I believe your best solution is to let the watchdog set a flag, and let the test read it at certain points. Similarly, your test can simply check the duration from time to time.

Note that if the "flag" would set in a way that will cause the main thread to raise an exception (for example, deleting attributes from objects), it'll be just as effective.

The other possibility is to use multiprocessing instead of multythreading, if it is possible for your application.