gpt4 book ai didi

python异常消息捕获

转载 作者:IT老高 更新时间:2023-10-28 12:04:27 25 4
gpt4 key购买 nike

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

关于python异常消息捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4690600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com