captura de mensajes de excepción de 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))

Esto no parece funcionar, tengo un error de sintaxis, ¿cuál es la forma correcta de hacer esto para registrar todo tipo de excepciones a un archivo

Author: Hellnar, 2011-01-14

9 answers

Debe definir qué tipo de excepción desea capturar. Por lo tanto, escriba except Exception, e: en lugar de except, e: para una excepción general (que se registrará de todos modos).

Otra posibilidad es escribir todo el código try / except de esta manera:

try:
    with open(filepath,'rb') as f:
        con.storbinary('STOR '+ filepath, f)
    logger.info('File successfully uploaded to '+ FTPADDR)
except Exception, e:
    logger.error('Failed to upload to ftp: '+ str(e))

En Python 3.x y versiones modernas de Python 2.x use except Exception as e en lugar de 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:
    logger.error('Failed to upload to ftp: '+ str(e))
 352
Author: eumiro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-18 09:23:29

La sintaxis ya no es soportada en python 3. Utilice lo siguiente en su lugar.

try:
    do_something()
except BaseException as e:
    logger.error('Failed to do something: ' + str(e))
 217
Author: sjtaheri,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-08 20:59:19

Actualizando esto a algo más simple para logger (funciona tanto para python 2 como para 3). No necesita el módulo de rastreo.

import logging

logger = logging.Logger('catch_all')

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

Este es ahora el antiguo camino (aunque todavía funciona):

import sys, traceback

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

Exc_value es el mensaje de error.

 24
Author: berniey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-10-30 22:59:33

Hay algunos casos en los que puedes usar e.message o e.messages.. Pero no funciona en todos los casos. De todos modos, lo más seguro es utilizar el str(e)

try:
  ...
except Exception as e:
  print(e.message)
 21
Author: Slipstream,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-02 09:11:58

Puede usar logger.exception("msg") para la excepción de registro con rastreo:

try:
    #your code
except Exception as e:
    logger.exception('Failed: ' + str(e))
 13
Author: Peter,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-10 12:09:03

Puede intentar especificar el tipo BaseException explícitamente. Sin embargo, esto solo capturará derivados de BaseException. Si bien esto incluye todas las excepciones proporcionadas por la implementación, también es posible que genere clases arbitrarias de estilo antiguo.

try:
  do_something()
except BaseException, e:
  logger.error('Failed to do something: ' + str(e))
 3
Author: Heini Høgnason,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-01-14 11:40:04

Si desea clase de error, mensaje de error y seguimiento de pila (o cualquiera de ellos), use sys.exec_info().

Código de trabajo mínimo con algún formato,

import sys
import traceback

try:
    ans = 1/0
except BaseException as ex:
    # Get current system exception
    ex_type, ex_value, ex_traceback = sys.exc_info()

    # Extract unformatter stack traces as tuples
    trace_back = traceback.extract_tb(ex_traceback)

    # Format stacktrace
    stack_trace = list()

    for trace in trace_back:
        stack_trace.append("File : %s , Line : %d, Func.Name : %s, Message : %s" % (trace[0], trace[1], trace[2], trace[3]))

    print("Exception type : %s " % ex_type.__name__)
    print("Exception message : %s" %ex_value)
    print("Stack trace : %s" %stack_trace)

Que dará salida siguiente,

Exception type : ZeroDivisionError
Exception message : division by zero
Stack trace : ['File : .\\test.py , Line : 5, Func.Name : <module>, Message : ans = 1/0']

Sys.exec_info()

Esto le da los detalles de la excepción sobre la excepción más reciente. Devuelve una tupla. Los siguientes son los valores de la tupla (type, value, traceback).

Traceback es una instancia de objeto traceback. Puede formatear la traza con proporcionado método. Se puede encontrar más en documentación de rastreo

 2
Author: Kavindu Dodanduwa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-02 14:55:16

Después de python 3.6, puede usar literal de cadena formateada. ¡Está limpio! ( https://docs.python.org/3/whatsnew/3.6.html#whatsnew36-pep498 )

try
 ...
except Exception as e:
    logger.error(f"Failed to upload to ftp: {e}")
 1
Author: Chuan Ma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-09-06 14:16:47

Utilice str(ex) para imprimir execption

try:
   #your code
except ex:
   print(str(ex))
 0
Author: Niraj Trivedi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-29 12:42:50