Cómo imprimir un error en Python?


try:
    something here
except:
    print 'the whatever error occurred.'

¿Cómo puedo imprimir el error en mi bloque except:?

Author: Slothworks, 2009-09-27

6 answers

Para Python 2.6 y posteriores y Python 3.x:

except Exception as e: print(e)

Para Python 2.5 y versiones anteriores, utilice:

except Exception,e: print str(e)
 499
Author: jldupont,
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-08-16 08:01:37

El traceback el módulo proporciona métodos para formatear e imprimir excepciones y sus rastreos, por ejemplo, esto imprimiría la excepción como lo hace el controlador predeterminado:

import traceback

try:
    1/0
except Exception:
    traceback.print_exc()

Salida:

Traceback (most recent call last):
  File "C:\scripts\divide_by_zero.py", line 4, in <module>
    1/0
ZeroDivisionError: division by zero
 237
Author: Cat Plus Plus,
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-19 15:44:27

{[2] {} En[3]}Python 2.6 o superior es un poco más limpio:

except Exception as e: print(e)

En versiones anteriores todavía es bastante legible:

except Exception, e: print e
 156
Author: ilya n.,
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
2014-06-02 13:42:25

En caso de que desee pasar cadenas de error, aquí hay un ejemplo de Errores y excepciones (Python 2.6)

>>> try:
...    raise Exception('spam', 'eggs')
... except Exception as inst:
...    print type(inst)     # the exception instance
...    print inst.args      # arguments stored in .args
...    print inst           # __str__ allows args to printed directly
...    x, y = inst          # __getitem__ allows args to be unpacked directly
...    print 'x =', x
...    print 'y =', y
...
<type 'exceptions.Exception'>
('spam', 'eggs')
('spam', 'eggs')
x = spam
y = eggs
 40
Author: Nick Dandoulakis,
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
2009-09-27 12:26:49

El aumento de un error de línea se puede hacer con declaraciones assert si eso es lo que desea hacer. Esto le ayudará a escribir código reparable estáticamente y comprobar los errores con anticipación.

assert type(A) is type(""), "requires a string"
 4
Author: whatnick,
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-06-01 15:15:56

(Iba a dejar esto como un comentario en la respuesta de @jldupont, pero no tengo suficiente reputación.)

También he visto respuestas como la de @jldupont en otros lugares. FWIW, creo que es importante tener en cuenta que esto:

except Exception as e:
    print(e)

Imprimirá la salida de error a sys.stdout por defecto. Un enfoque más apropiado para el manejo de errores en general sería:

except Exception as e:
    print(e, file=sys.stderr)

(Ten en cuenta que tienes que import sys para que esto funcione.) De esta manera, el error se imprime a STDERR en lugar de STDOUT, que permite el correcto análisis/redirección/etc. Entiendo que la pregunta era estrictamente sobre "imprimir un error", pero parece importante señalar la mejor práctica aquí en lugar de omitir este detalle que podría conducir a un código no estándar para cualquier persona que finalmente no aprenda mejor.

No he usado el módulo traceback como en la respuesta de Cat Plus Plus, y tal vez esa sea la mejor manera, pero pensé en lanzar esto por ahí.

 3
Author: grish,
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-21 19:38:43