e.printStackTrace equivalent in python

2022-08-31 05:36:03

I know that (where e is an Exception) prints the occurred exception but, I was trying to find the python equivalent of Java's that exactly traces the exception to what line it occurred and prints the entire trace of it.print(e)e.printStackTrace()

Could anyone please tell me the equivalent of in Python?e.printStackTrace()


答案 1
import traceback
traceback.print_exc()

When doing this inside an block it will automatically use the current exception. See http://docs.python.org/library/traceback.html for more information.except ...:


答案 2

There is also .logging.exception

import logging

...

try:
    g()
except Exception as ex:
    logging.exception("Something awful happened!")
    # will print this message followed by traceback

Output:

ERROR 2007-09-18 23:30:19,913 error 1294 Something awful happened!
Traceback (most recent call last):
  File "b.py", line 22, in f
    g()
  File "b.py", line 14, in g
    1/0
ZeroDivisionError: integer division or modulo by zero

(From http://blog.tplus1.com/index.php/2007/09/28/the-python-logging-module-is-much-better-than-print-statements/ via How to print the full traceback without halting the program?)


推荐