捕获python异常信息
import ftplib
import urllib2
import os
import logging
logger = logging.getLogger('ftpuploader')
hdlr = logging.FileHandler('ftplog.log')
formatter = logging.Formatter('%(asctime)s %(levelname)s %(message)s')
hdlr.setFormatter(formatter)
logger.addHandler(hdlr)
logger.setLevel(logging.INFO)
FTPADDR = "some ftp address"
def upload_to_ftp(con, filepath):
try:
f = open(filepath,'rb') # file to send
con.storbinary('STOR '+ filepath, f) # Send the file
f.close() # Close file and FTP
logger.info('File successfully uploaded to '+ FTPADDR)
except, e:
logger.error('Failed to upload to ftp: '+ str(e))
这似乎不太管用,我遇到了语法错误,正确的方法是什么,才能把所有类型的异常记录到一个文件里呢?
15 个回答
97
如果你想获取错误的类别、错误信息和调用栈,可以使用 sys.exc_info()
。
下面是一些格式化的简单示例代码:
import sys
import traceback
try:
ans = 1/0
except BaseException as ex:
# Get current system exception
ex_type, ex_value, ex_traceback = sys.exc_info()
# Extract unformatter stack traces as tuples
trace_back = traceback.extract_tb(ex_traceback)
# Format stacktrace
stack_trace = list()
for trace in trace_back:
stack_trace.append("File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]))
print("Exception type : %s " % ex_type.__name__)
print("Exception message : %s" %ex_value)
print("Stack trace : %s" %stack_trace)
运行后会得到以下输出:
Exception type : ZeroDivisionError
Exception message : division by zero
Stack trace : ['File : .\\test.py , Line : 5, Func.Name : <module>, Message : ans = 1/0']
这个 sys.exc_info() 函数会告诉你最近发生的错误的详细信息。它会返回一个包含 (类型, 值, 调用栈)
的元组。
调用栈
是一个 traceback 对象的实例。你可以使用提供的方法来格式化这个调用栈。想了解更多,可以查看 调用栈文档。
386
这种写法在Python 3中不再支持了。请使用下面的替代方法。
try:
do_something()
except BaseException as e:
logger.error('Failed to do something: ' + str(e))
1217
你需要先确定你想要捕捉哪种类型的错误。所以要写 except Exception as e:
,而不是 except, e:
来捕捉一般的错误。
另一种写法是把整个尝试/捕捉的代码这样写:
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to '+ FTPADDR)
except Exception as e: # works on python 3.x
logger.error('Failed to upload to ftp: %s', repr(e))
在旧版本的 Python 2.x 中,要用 except Exception, e
来代替 except Exception as e
:
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to %s', FTPADDR)
except Exception, e: # works on python 2.x
logger.error('Failed to upload to ftp: %s', repr(e))