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

时间:2012-03-12 22:38:45

标签: 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

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

TypeError
cannot concatenate 'str' and 'int' objects
None

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

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

1 个答案:

答案 0 :(得分:4)

尝试在my_excepthook中更改:

print "".join(traceback.format_exception(type, value, tb))