python - 是否可以捕获 Python 应用程序生成的任何回溯?

标签 python

我一直在谷歌上搜索一种方法来以某种方式捕获 Python 应用程序生成的任何回溯。

如果发生任何错误并生成回溯(而不是依赖用户向我报告问题),我想向自己发送电子邮件/slack/通知。

我还没有找到任何东西which doesn't involve you doing a try/except .但是我当然不能把我所做的一切都放在单独的 try/except 子句中,因为我正在编写启动 UI (PySide/PyQt4/PySide2/PyQt5) 的应用程序,并且可能会在用户交互时出错。

这是否可能,如果可以,我如何捕获生成的任何回溯?

最佳答案

您可以通过创建自定义 sys.excepthook 轻松做到这一点:

import sys
import traceback


def report_exception(exc_type, exc_value, exc_tb):
    # just a placeholder, you may send an e-mail here
    print("Type", exc_type)
    print("Value", exc_value)
    print("Tb", ''.join(traceback.format_tb(exc_tb)))


def custom_excepthook(exc_type, exc_value, exc_tb):
    report_exception(exc_type, exc_value, exc_tb)
    sys.__excepthook__(exc_type, exc_value, exc_tb)  # run standard exception hook


sys.excepthook = custom_excepthook

raise RuntimeError("I want to report exception here...")

对于 pretty-print 回溯对象,请参阅 traceback模块。

关于python - 是否可以捕获 Python 应用程序生成的任何回溯?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39815135/

相关文章:

python - 使用 XPATH 从特定表/网站获取数据

python - 如果您分块加载 csv,pandas dropna() 将不起作用

python - 更新了 Google App Engine,现在我的 python manage.py runserver 出现错误

python - 为什么 Python numpy float32/int 除法给出 float64 结果?

python - 在 sagemath 中定义函数的不同方式

Python:如何向数据帧的索引和列添加缺失值?

python - 无法在条目小部件上设置 focus()

python - 具有线性约束的 Scipy.optimize.minimize SLSQP 失败

python - Learning Object Detection 检测结果显示变色

python - 使用 Python Lambda 函数的 AWS ECR 图像标签