Python中捕捉詳細(xì)異常信息的代碼示例
更新時間:2014年09月18日 09:44:48 投稿:junjie
這篇文章主要介紹了Python中捕捉詳細(xì)異常信息的代碼示例,本文的代碼是從Python 2.7的源碼中得來,可以獲取文件位置、行號、函數(shù)、異常信息等內(nèi)容,需要的朋友可以參考下
大家在開發(fā)的過程中可能時常碰到一個需求,需要把Python的異常信息輸出到日志文件中。
網(wǎng)上的辦法都不太實(shí)用,下面介紹一種實(shí)用的,從Python 2.7源碼中扣出來的。
廢話不說 直接上代碼,代碼不多,注釋比較多而已。
import sys, traceback traceback_template = '''Traceback (most recent call last): File "%(filename)s", line %(lineno)s, in %(name)s %(type)s: %(message)s\n''' # Skipping the "actual line" item # Also note: we don't walk all the way through the frame stack in this example # see hg.python.org/cpython/file/8dffb76faacc/Lib/traceback.py#l280 # (Imagine if the 1/0, below, were replaced by a call to test() which did 1/0.) try: 1/0 except: # http://docs.python.org/2/library/sys.html#sys.exc_info exc_type, exc_value, exc_traceback = sys.exc_info() # most recent (if any) by default ''' Reason this _can_ be bad: If an (unhandled) exception happens AFTER this, or if we do not delete the labels on (not much) older versions of Py, the reference we created can linger. traceback.format_exc/print_exc do this very thing, BUT note this creates a temp scope within the function. ''' traceback_details = { 'filename': exc_traceback.tb_frame.f_code.co_filename, 'lineno' : exc_traceback.tb_lineno, 'name' : exc_traceback.tb_frame.f_code.co_name, 'type' : exc_type.__name__, 'message' : exc_value.message, # or see traceback._some_str() } del(exc_type, exc_value, exc_traceback) # So we don't leave our local labels/objects dangling # This still isn't "completely safe", though! # "Best (recommended) practice: replace all exc_type, exc_value, exc_traceback # with sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2] ## 修改這里就可以把traceback打到任意地方,或者存儲到文件中了 print traceback_template % traceback_details
相關(guān)文章
python命令行交互引導(dǎo)用戶選擇寵物實(shí)現(xiàn)
這篇文章主要為大家介紹了python命令行交互引導(dǎo)用戶選擇寵物實(shí)現(xiàn),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-11-11Python GUI編程學(xué)習(xí)筆記之tkinter中messagebox、filedialog控件用法詳解
這篇文章主要介紹了Python GUI編程學(xué)習(xí)筆記之tkinter中messagebox、filedialog控件用法,結(jié)合實(shí)例形式總結(jié)分析了Python GUI編程tkinter中messagebox、filedialog控件基本功能、用法與操作注意事項(xiàng),需要的朋友可以參考下2020-03-03pygame.display.flip()和pygame.display.update()的區(qū)別及說明
這篇文章主要介紹了pygame.display.flip()和pygame.display.update()的區(qū)別及說明,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-03-03