我无法弄清楚为什么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行的“无”,我希望得到当我注释掉sys.excepthook行时会发生什么:
Traceback (most recent call last):
File "log-test.py",line 17,in
最佳答案
尝试在my_excepthook中更改为:
print "".join(traceback.format_exception(type,tb))