在excepthook中打印原始异常

时间:2015-02-25 16:16:13

标签: python exception exception-handling

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

它会正确显示异常;但是,它也会在术语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'

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

1 个答案:

答案 0 :(得分:7)

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

from traceback import format_exception

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

sys.excepthook = self.excepthook

查看官方documentation了解更多信息和示例。