gpt4 book ai didi

python - 在 excepthook 中打印原始异常

转载 作者:太空狗 更新时间:2023-10-30 02:10:38 26 4
gpt4 key购买 nike

我正在设置 sys.excepthook 以便我可以记录发生的每个异常。我们不写入日志,而是使用以下示例:

def excepthook(self, type_, value, traceback):
print "\n"
print type_
print value
print traceback
print "\n"

sys.excepthook = self.excepthook

现在假设我创建了一个类型错误,如下所示:

print 3 + str(2)

在没有被捕获的情况下,它进入异常钩子(Hook)并正确打印出 3 个变量:

<type 'exceptions.TypeError'>
unsupported operand type(s) for +
<traceback object at 0x02BAE800>

我想做的是让它也打印出发送到异常钩子(Hook)的完整异常(因此,在本例中为 TypeException)。换句话说,我希望它也显示以下信息)。

Traceback (most recent call last):
File "testcidnelite.py", line 13, in <module>
print 3 + str(2)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

如果我添加以下行:

raise

它将正确显示异常;但是,它还会显示错误,其中包含术语 raise:

Error in sys.excepthook:
Traceback (most recent call last):
File "C:\psi-test-automation\Selenium\TestMethods2.py", line 145, in excepthook
raise
TypeError: exceptions must be old-style classes or derived from BaseException, not NoneType

修改为:

raise type_

会打印出如下错误:

Error in sys.excepthook:
Traceback (most recent call last):
File "C:\psi-test-automation\Selenium\TestMethods2.py", line 145, in excepthook
raise type_
TypeError

Original exception was:
Traceback (most recent call last):
File "testcidnelite.py", line 13, in <module>
print 3 + str(2)
TypeError: unsupported operand type(s) for +: 'int' and 'str'

我希望它只打印出第二个 block (原始异常)。这可能吗?

最佳答案

您可以使用 Python 的 traceback 模块来格式化异常。

from traceback import format_exception

def excepthook(self, type_, value, traceback):
print format_exception(type_, value, traceback)

sys.excepthook = self.excepthook

查看官方documentation获取更多信息和示例。

关于python - 在 excepthook 中打印原始异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28724032/

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