[python]python中,使用traceback处理异常信息

  近来编写一个程序,该程序可以在设定时间内,获取指定文件夹更新的文件夹和文件列表,并根据获取到的更新列表,做一些操作。由于所写程序是放在服务器上运行,为了保证程序在运行的过程中,不时不时跳出些异常信息出来吓其他用户,就在程序中添加了异常处理。将网上的资料整理下,试着将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 str
traceback: [('文件名', 行号, '函数名', '出现异常的代码行')]

在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 + "
"
11     errormsg += "value: " + evalue + "
"
12     errormsg += "traceback: " + str(etb) + "
"
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 + "
-------------------------------
"
26     usermsg += errormsg
27     fp.write(usermsg + "
")
28     fp.close()
View Code
原文地址:https://www.cnblogs.com/CaDevil/p/6043135.html