try:
1/0
except Exception,e:
print e
- 1
- 2
- 3
- 4
如果这样包起来错误的花,输出结果是integer division or modulo by zero,只知道是报了这个错,但是却不知道在哪个文件哪个函数哪一行报的错,还不如不包起来呢!
下面使用traceback模块
try:
1/0
except Exception,e:
traceback.print_exec()
- 1
- 2
- 3
- 4
输出结果是
Traceback (most recent call last):
File “test_traceback.py”, line 3, in
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文件去。
from:http://blog.youkuaiyun.com/handsomekang/article/details/9373035