[python]python中,使用traceback處理異常資訊

來源:互聯網
上載者:User

標籤:pat   time   value   dice   ack   localtime   alt   需要   for   

  近來編寫一個程式,該程式可以在設定時間內,擷取指定檔案夾更新的檔案夾和檔案清單,並根據擷取到的更新列表,做一些操作。由於所寫程式是放在伺服器上運行,為了保證程式在啟動並執行過程中,不時不時跳出些異常資訊出來嚇其他使用者,就在程式中添加了異常處理。將網上的資料整理下,試著將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

 

[python]python中,使用traceback處理異常資訊

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.