import traceback
try:
raiseSyntaxError, "traceback test"
except:
traceback.print_exc()
将会在控制台输出类似结果:
Traceback (most recent calllast):
File "H:PythonWorkSpaceTestsrcTracebackTest.py", line 3, in& lt;module>
raiseSyntaxError, "traceback test"
SyntaxError: traceback test
类似在你没有捕获异常时候, 解释器所返回的结果.
你也可以传入一个文件, 把返回信息写到文件中去, 如下:
import traceback
import StringIO
try:
raiseSyntaxError, "traceback test"
except:
fp =StringIO.StringIO()#创建内存文件对象
traceback.print_exc(file=fp)
message =fp.getvalue()
printmessage
这样在控制台输出的结果和上面例子一样
traceback模块还提供了extract_tb函数来格式化跟踪返回信息, 得到包含错误信息的列表, 如下:
import traceback
import sys
def tracebacktest():
raiseSyntaxError, "traceback test"
try:
tracebacktest()
except:
info =sys.exc_info()
for file,lineno, function, text in traceback.extract_tb(info[2]):
print file, "line:", lineno, "in", function
print text
print "**%s: %s" % info[:2]
H:PythonWorkSpaceTestsrcTracebackTest.pyline: 7 in <module>
tracebacktest()
H:PythonWorkSpaceTestsrcTracebackTest.py line: 5 intracebacktest
raise SyntaxError, "traceback test"
** <type 'exceptions.SyntaxError'>:traceback test