One - One Code All

Blog Content

python中打印输出详细异常信息traceback使用,异常的获取与处理

Python   2018-10-14 22:12:50

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())


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



上一篇:清除Laravel(终端)中的缓存
下一篇:Go开发中常见的坑1

The minute you think of giving up, think of the reason why you held on so long.