python中使用try exception时,打印完整出错代码追踪

使用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))

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
xiaoxingxing的头像xiaoxingxing管理团队
上一篇 2023年8月22日
下一篇 2023年8月22日

相关推荐