import traceback
try:
1/0
except Exception,e:
traceback.print_exc()
输出结果是
Traceback (most recent call last):
File "test_traceback.py", line 3, in <module>
1/0
ZeroDivisionError: integer division or modulo by zero
这样非常直观有利于调试。
traceback.print_exc()跟traceback.format_exc()有什么区别呢?
format_exc()返回字符串,print_exc()则直接给打印出来。
即traceback.print_exc()与print traceback.format_exc()效果是一样的。
print_exc()还可以接受file参数直接写入到一个文件。比如
traceback.print_exc(file=open('tb.txt','w+'))
写入到tb.txt文件去。
你也可以传入一个文件, 把返回信息写到文件中去, 如下:
|
1
2
3
4
5
6
7
8
9
|
import tracebackimport StringIOtry: raise SyntaxError, "traceback test"except: fp = StringIO.StringIO() #创建内存文件对象 traceback.print_exc(file=fp) message = fp.getvalue() print message |
这样在控制台输出的结果和上面例子一样,traceback模块还提供了extract_tb函数来格式化跟踪返回信息, 得到包含错误信息的列表, 如下:
|
1
2
3
4
5
6
7
8
9
10
11
12
|
import tracebackimport sysdef tracebacktest(): raise SyntaxError, "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] |
控制台输出结果如下:
|
1
2
3
4
5
|
H:PythonWorkSpaceTestsrcTracebackTest.py line: 7 in <module>tracebacktest()H:PythonWorkSpaceTestsrcTracebackTest.py line: 5 in tracebacktestraise SyntaxError, "traceback test"** <type 'exceptions.SyntaxError'>: traceback test |