使用模块 traceback
结合sys.exc_info()的输出(type, value, traceback):
type为出错的exception类型;
value 为具体为对应exception的错误描述信息;
traceback 为返回的该处exception的1个traceback类型;
try:
a = b+ c
except:
t, v, tb = sys.exc_info()
errstr = StringIO.StringIO()
test_tb = traceback.print_exception(t,v,tb,file=errstr)
print errstr.getvalue()
errstr.close()
#输出到file handle,结果为
Traceback (most recent call last):
File "1.py", line 4, in
a = b+ c
NameError: name 'b' is not defined
print traceback.extract_tb(tb)
# 输出(filename, line number,
function name, text)
[('1.py', 4, '', 'a = b+ c')]
print traceback.format_exception_only(t,v)
#输出1个list,只包括具体的exception error:
["NameError: name 'b' is not defined\n"]
print traceback.format_exception(t,v,tb)
#输出1个list,包括stack trace + exception information
['Traceback (most recent call last):\n',
' File "1.py", line 4, in \n a = b+ c\n',
"NameError: name 'b' is not defined\n"]
print traceback.format_tb(tb)
# A shorthand for format_list(extract_tb(tb, limit))
[' File "1.py", line 4, in \n a = b+ c\n']
print traceback.tb_lineno(tb)
# returns the current line number set in the traceback object
4
阅读(982) | 评论(0) | 转发(0) |