traceback用法(转载)

一、使用场景

程序出现异常,如何快速定位哪里错误。业务场景简单逐个检查, 复杂的就显得low。

a = 'hello world'
b = 12345

try:
    c = a + b
except TypeError as e:
    print(e)
输出 must be str, not int
带入代码中有N个这样try,如何定义,怎么快速查找问题位置,此时需要一个高效的查找工具traceback模块

二、 traceback 输出完整栈信息(调用顺序、错误语句、错误类型等)

1[.用法一]
转载https://blog.csdn.net/caoxinjian423/article/details/83714614

traceback.print_exc(limit=None, file=None, chain=True)
这是print_exception(*sys.exc_info(), limit, file, chain)一个便捷方法。
limit: 这个是限制stack trace层级的,如果不设或者为None,就会打印所有层级的stack trace
file: 这个是设置打印的输出流的,可以为文件,也可以是stdout之类的file-like object。如果不设或为None,则输出到sys.stderr。
chain:默认为True,也就是一并显示__cause__、__context__等串连起来的例外
import traceback

a = 'hello world'
b = 12345

try:
    c = a + b
except TypeError as e:

    # 将错误信息在终端输出
    traceback.print_exc()  
    
    # 将错误信息写入到tt文件夹内
    traceback.print_exc(limit=2, file=open('tt.log', 'a+'))  

输出错误信息出来了,错误文件,行数,原因

Traceback (most recent call last):
  File "C:/Users/allve/Desktop/tt.py", line 7, in <module>
    c = a + b
TypeError: must be str, not int

用法二

import sys

a = ['a', 'b', 'c', 'd']

try:
    b = a[4]
except IndexError as e:

    traceback.print_exc()
    
    exc_type, exc_value, exc_traceback = sys.exc_info()
    print(exc_type)   # type为异常类型
    print(exc_value)   # value为异常参数或错误信息
    print(traceback)   # 为跟踪回溯的对象
    
    ## traceback.print_exception(exc_type, exc_value, exc_traceback, file=open('tt.log', 'a+'))  # 日志记录

    for filename, linenum, funcname, source in traceback.extract_tb(exc_traceback):
        print("%-23s: %s '%s' in %s ()" % (filename, linenum, funcname, source))
        print(filename) # 错误文件
        print(linenum)  # 错误行号
        print(funcname) # 错误函数
        print(source)   # 错误资源

  • traceback.print_exc() 输出

    Traceback (most recent call last):
      File "C:/Users/allve/Desktop/tt.py", line 19, in <module>
        b = a[4]
    IndexError: list index out of range
  • exc_type输出

    <class 'IndexError'>
  • exc_value 输出

    list index out of range
  • traceback输出

    <module 'traceback' from 'c:\\users\\allve\\appdata\\local\\programs\\python\\python36\\lib\\traceback.py'>
  • filename, linenum, funcname, source

    C:/Users/allve/Desktop/tt/rainbow_bookII/lib/tt.py
    19
    <module>
    b = a[4]

评论

暂无评论