posts - 431,  comments - 344,  trackbacks - 0
公告
 Don't Repeat Yourself
座右铭:you can lose your money, you can spent all of it, and if you work hard you get it all back. But if you waste your time, you're never gonna get it back.
公告本博客在此声明部分文章为转摘,只做资料收集使用。


微信: szhourui
QQ:109450684
Email
lsi.zhourui@gmail.com
<2009年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

留言簿(15)

随笔分类(1019)

文章分类(3)

文章档案(21)

收藏夹

Link

好友博客

最新随笔

搜索

  •  

积分与排名

  • 积分 - 855923
  • 排名 - 47

最新评论

阅读排行榜

traceback模块被用来跟踪异常返回信息. 如下例所示:
import traceback
try:
    raise SyntaxError, "traceback test"
except:
    traceback.print_exc()

将会在控制台输出类似结果:
Traceback (most recent call last):
  File "H:\PythonWorkSpace\Test\src\TracebackTest.py", line 3, in <module>
    raise SyntaxError, "traceback test"
SyntaxError: traceback test

类似在你没有捕获异常时候, 解释器所返回的结果.
你也可以传入一个文件, 把返回信息写到文件中去, 如下:
import traceback
import StringIO
try:
    raise SyntaxError, "traceback test"
except:
    fp = StringIO.StringIO()    #创建内存文件对象
    traceback.print_exc(file=fp)
    message = fp.getvalue()
    print message

这样在控制台输出的结果和上面例子一样
traceback模块还提供了extract_tb函数来格式化跟踪返回信息, 得到包含错误信息的列表, 如下:

import traceback
import sys

def 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]

控制台输出结果如下:
H:\PythonWorkSpace\Test\src\TracebackTest.py line: 7 in <module>
tracebacktest()
H:\PythonWorkSpace\Test\src\TracebackTest.py line: 5 in tracebacktest
raise SyntaxError, "traceback test"
** <type 'exceptions.SyntaxError'>: traceback test




posted on 2009-06-17 21:37 周锐 阅读(9098) 评论(0)  编辑  收藏 所属分类: Python