python traceback使用 异常的获取与处理

1、traceback.print_exc()
2、traceback.format_exc()
3、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 "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module>
    func(1, 0)
  File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, in func
    return a / b
ZeroDivisionError: division by zero


***traceback.format_exc():*** 
Traceback (most recent call last):
  File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module>
    func(1, 0)
  File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, in func
    return a / b
ZeroDivisionError: division by zero


***traceback.print_exception():*** 
Traceback (most recent call last):
  File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 42, in <module>
    func(1, 0)
  File "E:/HttpRunnerManager-jh/ApiManager/tests.py", line 33, 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非常详情。

    try:
        func(1, 0)
    except Exception as e:
        import cgitb
        cgitb.enable(format='text')
        func(1, 0)

参考:
https://blog.csdn.net/lengxingxing_/article/details/56317838

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 9,670评论 4 16
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 14,743评论 0 38
  • 转载自:JmilkFan_范桂飓:http://blog.csdn.net/jmilk 异常 异常即非正常状态,在...
    ccq_inori阅读 9,098评论 0 1
  • 草没有黄 花儿没有谢 绿叶也还没有与枝桠分别 但是,别离啊 来的比草忙,比花儿急,比叶子的离开更加猝不及防 想和你...
    墨言0阅读 3,630评论 0 2
  • 我们之间,终成故事 希望你走的越远就有更好的风景,希望一别两宽,各生欢喜。 Z姑娘和先生L先生的相识像大多数平常的...
    xyz姑娘阅读 3,021评论 1 0