traceback

作者: shuff1e | 来源:发表于2018-03-20 22:08 被阅读6次
try:  
    1/0  
except Exception,e:  
    print e  

输出结果是integer division or modulo by zero,只知道是报了这个错,但是却不知道在哪个文件哪个函数哪一行报的错。

下面使用traceback模块

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文件去。

相关文章

网友评论

      本文标题:traceback

      本文链接:https://www.haomeiwen.com/subject/pgfqfftx.html