python的traceback用法

traceback模块被用来跟踪异常返回信息. 如下例所示:

1
2
3
4
5
import  traceback
try :
     raise  SyntaxError,  "traceback test"
except :
     traceback.print_exc()

将会在控制台输出类似结果:

1
2
3
4
Traceback (most recent call last):
   File "H:\PythonWorkSpace\Test\src\TracebackTest.py", line 3, in <module>
     raise SyntaxError, "traceback test"
SyntaxError: traceback test


类似在你没有捕获异常时候, 解释器所返回的结果.

你也可以传入一个文件, 把返回信息写到文件中去, 如下:

1
2
3
4
5
6
7
8
9
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函数来格式化跟踪返回信息, 得到包含错误信息的列表, 如下:


1
2
3
4
5
6
7
8
9
10
11
12
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 ]


控制台输出结果如下:

1
2
3
4
5
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


test1.py中,当分母为0的时候,调用系统退出。代码如下:


1
2
3
4
5
6
7
8
#!/usr/bin/python
import  sys
def  division(a = 1 , b = 1 ):
     if  b = = 0 :
          print  'b eq 0'
          sys.exit( 1 )
     else :
          return  a / b


test2.py中,用try..except捕获异常,然后traceback.print_exc()打印。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python
import  sys
import  traceback
import  test1
a = 10
b = 0
try :
     print  test1.division(a,b)
except :
     print  'invoking division failed.'
     traceback.print_exc()
     sys.exit( 1 )

执行test2.py失败抛出异常。

1
2
3
4
5
6
7
8
9
10
$python test2.py
execution python-2.5.1/python (enodeb/linux)
b eq 0
invoking division failed.
Traceback (most recent call last):
   File "test2.py", line 10, in <module>
     test1.division(a,b)
   File "/home/fesu/test1.py", line 6, in division
     sys.exit(1)
SystemExit: 1
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值