import sys
from twisted.internet import reactor, defer, task
from twisted.python import log
def periodic_task():
log.msg("periodic task running")
x = 10 / 0
def periodic_task_crashed(reason):
log.err(reason, "periodic_task broken")
log.startLogging(sys.stdout)
my_task = task.LoopingCall(periodic_task)
d = my_task.start(1)
d.addErrback(periodic_task_crashed)
reactor.run()
我正在获取输出,它会停止脚本。即使出现异常错误,有什么方法可以继续运行脚本吗?坦率地说,我正在执行一些 api 调用,而不是 x = 10/0 。但当出现错误时,它会停止脚本。但我想要的是即使有错误也运行脚本并一遍又一遍地检查。
最佳答案
只需处理异常,在您知道可能会失败的代码周围使用 try ... except block 。
def periodic_task():
log.msg("periodic task running")
try:
x = 10 / 0
except Exception as error:
# Here you should at least log the error, exceptions do not should pass silently.
pass
关于python - 循环调用Python中的异常绕过,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54262971/