【发布时间】:2011-06-09 02:27:48
【问题描述】:
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之后省略,。 -
@SvenMarnach,如果你在
except后面省略,,你会得到global name 'e' is not defined,这并不比语法错误好多少。 -
@Val: 应该是
except Exception as e或except Exception, e,取决于 Python 版本。 -
可能在这 8 个答案附近,但是当你打开一个文件时,关闭部分不应该在 try 语句中,而是在 finally 语句中或被 with 语句包裹。
-
你可以像请求包中的 UnitTests 那样做 fixexception.com/requests/expected-exception
标签: python exception logging except