美文网首页python
python traceback 异常的获取与处理

python traceback 异常的获取与处理

作者: wit92 | 来源:发表于2020-06-13 00:04 被阅读0次
    traceback.print_exc()
    traceback.format_exc()
    traceback.print_exception()
    

    简单说下这三个方法是做什么用的:

    1、print_exc():
        是对异常栈输出
    2、format_exc():
        是把异常栈以字符串的形式返回,print(traceback.format_exc()) 就相当于traceback.print_exc()
    3、print_exception():
        traceback.print_exc()实现方式就是traceback.print_exception(sys.exc_info()),可以点        sys.exc_info()进去看看实现
    

    测试代码如下:

    def func(a, b):
        return a / b
    
    
    if __name__ == '__main__':
        import sys
        import time
        import traceback
    
        try:
            func(1, 0)
        except Exception as e:
            print('***', type(e), e, '***')
            time.sleep(2)
    
            print("***traceback.print_exc():*** ")
            time.sleep(1)
            traceback.print_exc()
            time.sleep(2)
    
            print("***traceback.format_exc():*** ")
            time.sleep(1)
            print(traceback.format_exc())
            time.sleep(2)
    
            print("***traceback.print_exception():*** ")
            time.sleep(1)
            traceback.print_exception(*sys.exc_info())
    

    运行结果:

    *** <class 'ZeroDivisionError'> division by zero ***
    ***traceback.print_exc():*** 
    Traceback (most recent call last):
      File "/home/l/PycharmProjects/test_modules/tasks.py", line 26, in <module>
        func(1, 0)
      File "/home/l/PycharmProjects/test_modules/tasks.py", line 17, in func
        return a / b
    ZeroDivisionError: division by zero
    ***traceback.format_exc():*** 
    Traceback (most recent call last):
      File "/home/l/PycharmProjects/test_modules/tasks.py", line 26, in <module>
        func(1, 0)
      File "/home/l/PycharmProjects/test_modules/tasks.py", line 17, in func
        return a / b
    ZeroDivisionError: division by zero
    
    ***traceback.print_exception():*** 
    Traceback (most recent call last):
      File "/home/l/PycharmProjects/test_modules/tasks.py", line 26, in <module>
        func(1, 0)
      File "/home/l/PycharmProjects/test_modules/tasks.py", line 17, in func
        return a / b
    ZeroDivisionError: division by zero
    

    可以看出,三种方式打印结果是一样的。在开发时,做调试是很方便的。也可以把这种异常栈写入日志。

    logging.exception(ex)
    
    # 指名输出栈踪迹, logging.exception的内部也是包了一层此做法
    logging.error(ex, exc_info=1) 
    
    # 更加严重的错误级别 
    logging.critical(ex, exc_info=1) 
    
    # 我直接copy的,未尝试。有时间会试下的
    
    

    python 还有一个模块叫cgitb,输出的error非常详情。

    # -*- coding: utf-8 -*-
    def func(a, b):
        return a / b
    
    try:
        func(1, 0)
    except Exception as e:
        import cgitb
        cgitb.enable(format='text')
        func(1, 0)
    

    控制台打印结果

    相关文章

      网友评论

        本文标题:python traceback 异常的获取与处理

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