Python中使用try-except语句打印完整的错误追踪代码

使用python程序时,不使用try exception时,虽然能打印完整的出错代码追踪,但是会发生异常崩溃导致程序卡死;启用try exception后,一般也只能打印异常类型和异常信息,无法直接获取到出错代码行和代码追踪信息,找到的解决办法有这么两个。

1.使用python自带的traceback模块

亲测python3.5和python3.8都自带了该模块,使用代码如下所示:

import traceback

def test(a):
    b =int(a)
    print(b)

print(dir(traceback))
try:
   test('10')
   test('sa')
except Exception as e:
   print(type(e))
   print(str(e))
   traceback.print_exc()
   traceback.print_exc(file=open('log.txt', 'a'))

2.直接使用exception的属性获取出错行文件和行数

def test(a):
    b =int(a)
    print(b)

try:
   test('10')
   test('sa')
except Exception as e:
   print(type(e))
   print(str(e))
   print('error file:{}'.format(e.__traceback__.tb_frame.f_globals["__file__"]))
   print('error line:{}'.format(e.__traceback__.tb_lineno))

物联沃分享整理
物联沃-IOTWORD物联网 » Python中使用try-except语句打印完整的错误追踪代码

发表评论