Python异常模块traceback用法举例

来源:互联网 发布:怎样淘宝上降价买东西 编辑:程序博客网 时间:2024/05/18 03:20

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




转自:http://www.169it.com/article/3213819537.html

0 0
原创粉丝点击