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

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


当前回答

还有一种方法可以获得传递给异常类的原始值,而不必更改内容类型。

例如,我在我的一个框架中生成带有错误消息的类型代码。

try:
    # TODO: Your exceptional code here 
    raise Exception((1, "Your code wants the program to exit"))

except Exception as e:
    print("Exception Type:", e.args[0][0], "Message:", e.args[0][1])

输出

Exception Type: 1 Message: 'Your code wants the program to exit'

其他回答

可以尝试显式指定BaseException类型。然而,这只会捕获BaseException的派生。虽然这包括所有实现提供的异常,但也可能引发任意的旧式类。

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

还有一种方法可以获得传递给异常类的原始值,而不必更改内容类型。

例如,我在我的一个框架中生成带有错误消息的类型代码。

try:
    # TODO: Your exceptional code here 
    raise Exception((1, "Your code wants the program to exit"))

except Exception as e:
    print("Exception Type:", e.args[0][0], "Message:", e.args[0][1])

输出

Exception Type: 1 Message: 'Your code wants the program to exit'

使用str(ex)打印执行

try:
   #your code
except ex:
   print(str(ex))

在Python 3中,str(ex)向我们提供了错误消息。您可以使用repr(ex)获取全文,包括引发的异常的名称。

arr = ["a", "b", "c"]

try:
    print(arr[5])
except IndexError as ex:
    print(repr(ex)) # IndexError: list index out of range
    print(str(ex)) # list index out of range

如果要查看原始错误消息,(文件行号)

import traceback
try:
    print(3/0)
except Exception as e:    
    traceback.print_exc() 

这将显示相同的错误消息,就像您没有使用try-except一样。