[python]python中,使用traceback處理異常資訊,pythontraceback
近來編寫一個程式,該程式可以在設定時間內,擷取指定檔案夾更新的檔案夾和檔案清單,並根據擷取到的更新列表,做一些操作。由於所寫程式是放在伺服器上運行,為了保證程式在啟動並執行過程中,不時不時跳出些異常資訊出來嚇其他使用者,就在程式中添加了異常處理。將網上的資料整理下,試著將sys.exce_info()和traceback搭配一起使用。效果還算不錯,以下資訊是我當前處理異常的方式,其中type是異常的類型,value是出現異常的原因,traceback則是通過traceback追中到的異常資訊,能夠定位到造成異常的代碼。
2016-11-07 22:07:56-------------------------------type: <type 'exceptions.TypeError'>value: string indices must be integers, not strtraceback: [('檔案名稱', 行號, '函數名', '出現異常的程式碼')]
在try...except中,使用下述兩行記錄異常情況。針對出現異常之後如何程式如何繼續之後的工作,則需要看具體要求。
tp,val,td = sys.exc_info()Log.logerexception(tp,val,td)
具體代碼如下
1 import os 2 import time 3 import traceback 4 import sys 5 6 def logerexception(tp,val,td): 7 etype = str(tp) 8 evalue = str(val) 9 etb = traceback.extract_tb(td)10 errormsg = "type: " + etype + "\n"11 errormsg += "value: " + evalue + "\n"12 errormsg += "traceback: " + str(etb) + "\n"13 writetofile(errormsg)14 15 def writetofile(errormsg):16 logfilepath = os.path.abspath('.') + "/log"17 if not os.path.exists(logfilepath):18 os.mkdir(logfilepath)19 20 logfile = time.strftime("%Y%m%d", time.localtime()) + ".txt"21 fp = open(logfilepath + "/" + logfile,"a")22 ISOTIMEFORMAT= "%Y-%m-%d %X"23 happeningtime = time.strftime(ISOTIMEFORMAT, time.localtime())24 usermsg = ""25 usermsg += happeningtime + "\n-------------------------------\n"26 usermsg += errormsg27 fp.write(usermsg + "\n")28 fp.close()View Code