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

這彷佛不起做用,出現語法錯誤,將全部類型的異常記錄到文件中的正確方法是什麼 python


#1樓

python 3再也不支持該語法。請改用如下內容。 安全

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

#2樓

將其更新爲更簡單的記錄器(適用於python 2和3)。 您不須要回溯模塊。 url

import logging

logger = logging.Logger('catch_all')

def catchEverythingInLog():
    try:
        ... do something ...
    except Exception as e:
        logger.error(e, exc_info=True)
        ... exception handling ...

如今這是舊方法(儘管仍然有效): spa

import sys, traceback

def catchEverything():
    try:
        ... some operation(s) ...
    except:
        exc_type, exc_value, exc_traceback = sys.exc_info()
        ... exception handling ...

exc_value是錯誤消息。 code


#3樓

您能夠使用logger.exception("msg")來記錄帶有回溯的異常: orm

try:
    #your code
except Exception as e:
    logger.exception('Failed: ' + str(e))

#4樓

在某些狀況下,您能夠使用e.messagee.messages ..可是,並不是在全部狀況下都有效。 不管如何,使用str(e)更安全 get

try:
  ...
except Exception as e:
  print(e.message)

#5樓

您能夠嘗試明確指定BaseException類型。 可是,這隻會捕獲BaseException的派生類。 儘管這包括全部實現提供的異常,但也有可能引起任意舊式類。 io

try:
  do_something()
except BaseException, e:
  logger.error('Failed to do something: ' + str(e))
相關文章
相關標籤/搜索