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))

这似乎不起作用,我收到语法错误,将所有类型的异常记录到文件的正确方法是什么

原文由 Hellnar 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 235
2 个回答

您必须定义要捕获的异常类型。所以写 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: # work on python 2.x
    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: # work on python 3.x
    logger.error('Failed to upload to ftp: '+ str(e))

原文由 eumiro 发布,翻译遵循 CC BY-SA 4.0 许可协议

python 3 不再支持该语法。请改用以下内容。

 try:
    do_something()
except BaseException as e:
    logger.error('Failed to do something: ' + str(e))

原文由 sjtaheri 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题