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))
这似乎不起作用,我得到了语法错误,对于将所有类型的异常记录到文件中的正确方法是什么?
你必须定义你想捕捉哪种类型的异常。所以写except Exception, e:
而不是except, e:
来捕捉一般的异常(反正会被记录)。
其他的可能性是这样写你的整个try/except代码。
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to '+ FTPADDR)
except Exception, e:
logger.error('Failed to upload to ftp: '+ str(e))
在Python 3.x和Python 2.x的现代版本中,使用 "except Exception as e",而不是 "except Exception, e"。
try:
with open(filepath,'rb') as f:
con.storbinary('STOR '+ filepath, f)
logger.info('File successfully uploaded to '+ FTPADDR)
except Exception as e:
logger.error('Failed to upload to ftp: '+ str(e))