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))
这似乎不起作用,我收到语法错误,将所有类型的异常记录到文件的正确方法是什么
原文由 Hellnar 发布,翻译遵循 CC BY-SA 4.0 许可协议
您必须定义要捕获的异常类型。所以写
except Exception, e:
而不是except, e:
作为一般异常(无论如何都会记录下来)。另一种可能性是以这种方式编写整个 try/except 代码:
在 Python 3.x 和现代版本的 Python 2.x 中使用
except Exception as e
而不是except Exception, e
: