在期待回溯时,traceback.format_exc/print_exc返回None

Jus*_*att 5 python exception-handling

我无法弄清楚为什么traceback.format_exc()在以下示例中返回"None":

#!/usr/bin/env python

import sys
import traceback

def my_excepthook(type, value, tb):
    print type.__name__
    print value
    # the problem: why does this return "None"?
    print traceback.format_exc(tb) # see http://docs.python.org/library/traceback.html#traceback.format_exc

sys.excepthook = my_excepthook # see http://docs.python.org/library/sys.html#sys.excepthook

# some code to generate a naturalistic exception
a = "text"
b = 5
error = a + b
Run Code Online (Sandbox Code Playgroud)

使用Python 2.7.1,我得到以下输出:

TypeError
cannot concatenate 'str' and 'int' objects
None
Run Code Online (Sandbox Code Playgroud)

而不是第3行的"无",我希望得到当我注释掉sys.excepthook行时会发生什么:

Traceback (most recent call last):
  File "log-test.py", line 17, in <module>
    error = a+b 
Run Code Online (Sandbox Code Playgroud)

Pas*_*eBT 5

尝试在 my_excepthook 中像这样更改:

print "".join(traceback.format_exception(type, value, tb))
Run Code Online (Sandbox Code Playgroud)