gpt4 book ai didi

Python 捕获任何异常,并使用变量值打印或记录回溯

转载 作者:太空狗 更新时间:2023-10-29 22:23:34 25 4
gpt4 key购买 nike

当我使用 sys.excepthook 发现意外错误时

import sys
import traceback

def handleException(excType, excValue, trace):
print 'error'
traceback.print_exception(excType, excValue, trace)

sys.excepthook = handleException

h = 1
k = 0

print h/k

这是我得到的输出

error
Traceback (most recent call last):
File "test.py", line 13, in <module>
print h/k
ZeroDivisionError: integer division or modulo by zero

如何在回溯中包含变量值(h、k、...),类似于 http://www.doughellmann.com/PyMOTW/cgitb/ ?当我包含 cgitb 结果是一样的。

编辑:

很好的答案我只是像这样修改它所以它在文件中记录跟踪

def handleException(excType, excValue, trace):
cgitb.Hook(logdir=os.path.dirname(__file__),
display=False,
format='text')(excType, excValue, trace)

最佳答案

通过查看 cgitb.py 的源代码,您应该能够使用如下内容:

import sys
import traceback
import cgitb

def handleException(excType, excValue, trace):
print 'error'
cgitb.Hook(format="text")(excType, excValue, trace)

sys.excepthook = handleException

h = 1
k = 0

print h/k

关于Python 捕获任何异常,并使用变量值打印或记录回溯,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8702230/

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