python - 循环调用Python中的异常绕过

标签 python python-3.x

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/

相关文章:

javascript - 从 python Appengine 中的 Javascript 函数检索变量

python - 将列表中的值附加到字典中

django - 如何在 django Rest 框架中跳过或删除 simplejwt token 身份验证中的密码字段?

python - 将列表列表(表示边)中的数据加载到 python 中的 igraph 图中

python - 在 h5py 中混合高级和低级接口(interface)

python - 在 python v3.3 中将 8 位值写入二进制文件

python - 从元组列表中获取其元素之间差异最大的元组

python - 如何通过Panda导入几年但特定月份的数据?

python - 机器学习随机森林

python - 单击 QTextDocument 中的链接生成自定义事件