python – 在excepthook中打印原始异常

我正在设置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)

没有被抓住,这进入了异常情况并正确打印出3个变量:

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

我想做的是,它还打印出发送到excepthook的完整异常(因此,在这种情况下,是一个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

它会正确显示异常;但是,它也会在术语“加速”时显示错误:

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'

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

最佳答案 您可以使用Python的traceback模块来格式化异常.

from traceback import format_exception

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

sys.excepthook = self.excepthook

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

点赞