python3 使用traceback定位異常實例
1、我們使用正常的輸出語句
得到的是(輸出結(jié)果:division by zero)雖然得到了錯誤的日志輸出,但是不知道為什么出錯,也不能定位具體出錯位置。
2、現(xiàn)在我們使用 traceback
就可以得到具體的錯誤,以及定位到出錯的位置。這樣就能更方便調(diào)試錯誤。
參考文獻
traceback文檔地址:
https://docs.python.org/2/library/traceback.html
以下為google翻譯(僅供參考,):
該模塊提供了一個標準接口,用于提取,格式化和打印Python程序的堆棧跟蹤。它在打印堆棧跟蹤時完全模仿了Python解釋器的行為。當您想要在程序控制下打印堆棧跟蹤時,這非常有用,例如在解釋器周圍的“包裝器”中。
該模塊使用回溯對象 - 這是存儲在變量中的對象類型sys.exc_traceback(不建議使用), sys.last_traceback并作為第三項返回 sys.exc_info()。
該模塊定義了以下功能:
traceback.print_tb(tb [,limit [,file ] ] )
打印以限制回溯對象tb中的堆棧跟蹤條目。如果 省略limit或者None打印所有條目。如果省略文件或None輸出轉(zhuǎn)到sys.stderr; 否則它應(yīng)該是一個打開的文件或類似文件的對象來接收輸出。
traceback.print_exception(etype,value,tb [,limit [,file ] ] )
打印異常信息,最多限制堆棧跟蹤條目從traceback tb到文件。這與print_tb()以下方式不同:(1)如果tb不是None,則打印標題; (2)在堆棧跟蹤后打印異常etype和值 ; (3)如果etype是且值具有適當?shù)母袷?,則打印出發(fā)生語法錯誤的行,其中插入符號表示錯誤的大致位置。Traceback (most recent call last):SyntaxError
traceback.print_exc([ limit [,file ] ] )
這是一個簡寫。(實際上,它用于以線程安全的方式檢索相同的信息,而不是使用已棄用的變量。)print_exception(sys.exc_type, sys.exc_value, sys.exc_traceback, limit, file)sys.exc_info()
traceback.format_exc([ 限制] )
這就像print_exc(limit)但返回一個字符串而不是打印到文件。
版本2.4中的新功能。
traceback.print_last([ limit [,file ] ] )
這是一個簡寫。通常,只有在異常達到交互式提示后才會起作用(請參閱參考資料)。print_exception(sys.last_type, sys.last_value, sys.last_traceback, limit, file)sys.last_type
traceback.print_stack([ f [,limit [,file ] ] ] )
此函數(shù)從其調(diào)用點打印堆棧跟蹤??蛇x的 f參數(shù)可用于指定要啟動的備用堆棧幀??蛇x的limit和file參數(shù)具有相同的含義 print_exception()。
traceback.extract_tb(tb [,限制] )
返回從追溯對象tb中提取的最多限制 “預(yù)處理”堆棧跟蹤條目的列表。它對堆棧跟蹤的替代格式化很有用。如果省略limit,則提取所有條目?!邦A(yù)處理”堆棧跟蹤條目是4元組(文件名,行號,函數(shù)名*,文本),表示通常為堆棧跟蹤打印的信息。該文本是開頭和結(jié)尾的空白剝離的字符串; 如果源不可用則是。NoneNone
traceback.extract_stack([ f [,limit ] ] )
從當前堆棧幀中提取原始回溯。返回值的格式與extract_tb()??蛇x的f和limit 參數(shù)具有與之相同的含義print_stack()。
traceback.format_list(extracted_list )
給定由extract_tb()or extract_stack()返回的元組列表,返回準備打印的字符串列表。結(jié)果列表中的每個字符串對應(yīng)于參數(shù)列表中具有相同索引的項。每個字符串以換行符結(jié)尾; 對于那些源文本行不是的項目,字符串也可以包含內(nèi)部換行符 None。
traceback.format_exception_only(etype,value )
格式化回溯的異常部分。參數(shù)是異常類型,etype和值,例如由sys.last_type和 給出的sys.last_value。返回值是一個字符串列表,每個字符串以換行符結(jié)尾。通常,列表包含單個字符串; 但是,對于 SyntaxError異常,它包含多行(打印時)顯示有關(guān)語法錯誤發(fā)生位置的詳細信息。指示發(fā)生了哪個異常的消息是列表中的始終最后一個字符串。
traceback.format_exception(etype,value,tb [,limit ] )
格式化堆棧跟蹤和異常信息。參數(shù)與相應(yīng)的參數(shù)具有相同的含義print_exception()。返回值是一個字符串列表,每個字符串以換行符結(jié)尾,一些包含內(nèi)部換行符。連接和打印這些行時,將打印完全相同的文本print_exception()。
traceback.format_tb(tb [,限制] )
簡寫。format_list(extract_tb(tb, limit))
traceback.format_stack([ f [,limit ] ] )
簡寫。format_list(extract_stack(f, limit))
traceback.tb_lineno(tb )
此函數(shù)返回traceback對象中設(shè)置的當前行號。這個函數(shù)是必要的,因為在2.3之前的Python版本中,當-O標志傳遞給Python時,tb.tb_lineno沒有正確更新。此功能在2.3版本中沒有用處。
回溯示例
這個簡單的例子實現(xiàn)了一個基本的read-eval-print循環(huán),類似于標準Python交互式解釋器循環(huán)(但不太有用)。有關(guān)解釋器循環(huán)的更完整實現(xiàn),請參閱該code 模塊。
import sys, traceback def run_user_code(envdir): source = raw_input(">>> ") try: exec source in envdir except: print "Exception in user code:" print '-'*60 traceback.print_exc(file=sys.stdout) print '-'*60 envdir = {} while 1: run_user_code(envdir)
以下示例演示了打印和格式化異常和回溯的不同方法:
import sys, traceback def lumberjack(): bright_side_of_death() def bright_side_of_death(): return tuple()[0] try: lumberjack() except IndexError: exc_type, exc_value, exc_traceback = sys.exc_info() print "*** print_tb:" traceback.print_tb(exc_traceback, limit=1, file=sys.stdout) print "*** print_exception:" traceback.print_exception(exc_type, exc_value, exc_traceback, limit=2, file=sys.stdout) print "*** print_exc:" traceback.print_exc() print "*** format_exc, first and last line:" formatted_lines = traceback.format_exc().splitlines() print formatted_lines[0] print formatted_lines[-1] print "*** format_exception:" print repr(traceback.format_exception(exc_type, exc_value, exc_traceback)) print "*** extract_tb:" print repr(traceback.extract_tb(exc_traceback)) print "*** format_tb:" print repr(traceback.format_tb(exc_traceback)) print "*** tb_lineno:", exc_traceback.tb_lineno
該示例的輸出看起來類似于:
*** print_tb: File "<doctest...>", line 10, in <module> lumberjack() *** print_exception: Traceback (most recent call last): File "<doctest...>", line 10, in <module> lumberjack() File "<doctest...>", line 4, in lumberjack bright_side_of_death() IndexError: tuple index out of range *** print_exc: Traceback (most recent call last): File "<doctest...>", line 10, in <module> lumberjack() File "<doctest...>", line 4, in lumberjack bright_side_of_death() IndexError: tuple index out of range *** format_exc, first and last line: Traceback (most recent call last): IndexError: tuple index out of range *** format_exception: ['Traceback (most recent call last):\n', ' File "<doctest...>", line 10, in <module>\n lumberjack()\n', ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n', ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n', 'IndexError: tuple index out of range\n'] *** extract_tb: [('<doctest...>', 10, '<module>', 'lumberjack()'), ('<doctest...>', 4, 'lumberjack', 'bright_side_of_death()'), ('<doctest...>', 7, 'bright_side_of_death', 'return tuple()[0]')] *** format_tb: [' File "<doctest...>", line 10, in <module>\n lumberjack()\n', ' File "<doctest...>", line 4, in lumberjack\n bright_side_of_death()\n', ' File "<doctest...>", line 7, in bright_side_of_death\n return tuple()[0]\n'] *** tb_lineno: 10
以下示例顯示了打印和格式化堆棧的不同方法:
import traceback def another_function(): lumberstack() def lumberstack(): traceback.print_stack() print repr(traceback.extract_stack()) print repr(traceback.format_stack()) another_function() File "<doctest>", line 10, in <module> another_function() File "<doctest>", line 3, in another_function lumberstack() File "<doctest>", line 6, in lumberstack traceback.print_stack() [('<doctest>', 10, '<module>', 'another_function()'), ('<doctest>', 3, 'another_function', 'lumberstack()'), ('<doctest>', 7, 'lumberstack', 'print repr(traceback.extract_stack())')] [' File "<doctest>", line 10, in <module>\n another_function()\n', ' File "<doctest>", line 3, in another_function\n lumberstack()\n', ' File "<doctest>", line 8, in lumberstack\n print repr(traceback.format_stack())\n']
最后一個示例演示了最后幾個格式化函數(shù):
import traceback traceback.format_list([('spam.py', 3, '<module>', 'spam.eggs()'), ('eggs.py', 42, 'eggs', 'return "bacon"')]) [' File "spam.py", line 3, in <module>\n spam.eggs()\n', ' File "eggs.py", line 42, in eggs\n return "bacon"\n'] an_error = IndexError('tuple index out of range') traceback.format_exception_only(type(an_error), an_error) ['IndexError: tuple index out of range\n']
以上這篇python3 使用traceback定位異常實例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
pd.DataFrame統(tǒng)計各列數(shù)值多少的實例
今天小編就為大家分享一篇pd.DataFrame統(tǒng)計各列數(shù)值多少的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-12-12python實現(xiàn)zabbix發(fā)送短信腳本
這篇文章主要為大家詳細介紹了python實現(xiàn)zabbix發(fā)送短信腳本,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-09-09如何使用 Python和 FFmpeg 批量截圖視頻到各自文件夾中
wxPython 提供了一個簡單易用的界面,而 FFmpeg 則負責處理視頻幀的提取,這個工具不僅對視頻編輯工作有幫助,也為批量處理視頻文件提供了極大的便利,這篇文章主要介紹了使用 Python和 FFmpeg 批量截圖視頻到各自文件夾中,需要的朋友可以參考下2024-08-08python標準庫sys和OS的函數(shù)使用方法與實例詳解
這篇文章主要介紹了python標準庫sys和OS的函數(shù)使用方法與實例詳解,需要的朋友可以參考下2020-02-02