Python捕獲異常堆棧信息的幾種方法(小結(jié))
程序出錯(cuò)的時(shí)候,我們往往需要根據(jù)異常信息來找到具體出錯(cuò)的代碼。簡(jiǎn)單地用print打印異常信息并不能很好地追溯出錯(cuò)的代碼:
# -*- coding: utf-8 -*-
def foo(a, b):
c = a + b
raise ValueError('test')
return c
def bar(a):
print('a + 100:', foo(a, 100))
def main():
try:
bar(100)
except Exception as e:
print(repr(e))
if __name__ == '__main__':
main()
輸出:
ValueError('test',)
打印的異常信息不夠詳細(xì),對(duì)錯(cuò)誤追蹤沒有多大幫助。這時(shí)候異常堆棧信息就派上用場(chǎng)了。下面簡(jiǎn)單介紹幾種打印異常堆棧信息的方法。
1.最簡(jiǎn)單的方法之一就是使用logging.exception
# -*- coding: utf-8 -*-
import logging
def foo(a, b):
c = a + b
raise ValueError('test')
return c
def bar(a):
print('a + 100:', foo(a, 100))
def main():
try:
bar(100)
except Exception as e:
logging.exception(e)
if __name__ == '__main__':
main()
輸出:
ERROR:root:test
Traceback (most recent call last):
File "E:/git_work/scrapy_ppt/test.py", line 16, in main
bar(100)
File "E:/git_work/scrapy_ppt/test.py", line 11, in bar
print('a + 100:', foo(a, 100))
File "E:/git_work/scrapy_ppt/test.py", line 6, in foo
raise ValueError('test')
ValueError: test
從異常堆棧信息中我們可以不費(fèi)力氣就找出錯(cuò)誤代碼是哪一行。
2.其它方法:
# -*- coding: utf-8 -*-
import traceback
import sys
def foo(a, b):
c = a + b
raise ValueError('test')
return c
def bar(a):
print('a + 100:', foo(a, 100))
def main():
try:
bar(100)
except Exception as e:
# 方法二
traceback.print_exc()
# 方法三
msg = traceback.format_exc()
print(msg)
et, ev, tb = sys.exc_info()
# 方法四
traceback.print_tb(tb)
# 方法五
traceback.print_exception(et, ev, tb)
# 方法六
msg = traceback.format_exception(et, ev, tb)
for m in msg:
print(m)
if __name__ == '__main__':
main()
到此這篇關(guān)于Python捕獲異常堆棧信息的幾種方法(小結(jié))的文章就介紹到這了,更多相關(guān)Python捕獲異常堆棧信息內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python淘寶或京東等秒殺搶購腳本實(shí)現(xiàn)(秒殺腳本)
本篇文章主要介紹了Python 通過selenium實(shí)現(xiàn)毫秒級(jí)自動(dòng)搶購的示例代碼,通過掃碼登錄即可自動(dòng)完成一系列操作,搶購時(shí)間精確至毫秒,可搶加購物車等待時(shí)間結(jié)算的,也可以搶聚劃算、火車票等的商品,感興趣的朋友跟隨小編一起看看吧2022-10-10
PyCharm MySQL可視化Database配置過程圖解
這篇文章主要介紹了PyCharm MySQL可視化Database配置過程圖解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-06-06
使用Python讀取Excel數(shù)據(jù)在PPT中創(chuàng)建圖表
使用Python從Excel讀取數(shù)據(jù)并在PowerPoint幻燈片中創(chuàng)建圖表不僅能夠極大地簡(jiǎn)化圖表創(chuàng)建過程,通過Python這一橋梁,我們可以輕松實(shí)現(xiàn)數(shù)據(jù)自動(dòng)化處理和圖表生成,本文將演示如何使用Python讀取Excel數(shù)據(jù)在PPT中創(chuàng)建圖表,需要的朋友可以參考下2024-08-08
Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)對(duì)切片命名清除索引的方法
這篇文章主要介紹了Python cookbook(數(shù)據(jù)結(jié)構(gòu)與算法)對(duì)切片命名清除索引的方法,結(jié)合實(shí)例形式分析了Python字符串截取及indices方法映射序列的相關(guān)操作技巧,需要的朋友可以參考下2018-03-03
python使用遞歸實(shí)現(xiàn)斐波那契數(shù)列的示例詳解
這篇文章主要給大家介紹了python使用遞歸實(shí)現(xiàn)斐波那契數(shù)列的示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者使用Python具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起來學(xué)習(xí)吧2024-01-01
Python連接Mssql基礎(chǔ)教程之Python庫pymssql
python使用Tesseract庫識(shí)別驗(yàn)證

