gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 14:59:10 25 4
gpt4 key购买 nike

我一直在谷歌上搜索一种方法来以某种方式捕获 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com