How to generate java like stack trace in python?

In my experience programming with Java, I have become quite fond of the stack traces it generates when my code goes awry, but I feel that the traces generated by python are a bit lacking by comparison. For example, a trace in java might look like this:

java.lang.RuntimeException
    at test.package.Example.c(Example.java:20)
    at test.package.Example.b(Example.java:15)
    at test.package.Example.a(Example.java:10)

Whereas a python trace might look like this:

Traceback (most recent call last):
  File "example.py", line 10, in <module>
    a()
  File "example.py", line 2, in a
    b()
  File "example.py", line 5, in b
    c()
  File "example.py", line 8, in c
    raise Exception
Exception

While both of these traces convey basically the same information, I personally find that the trace from java is easier to follow.

Is there a means to change the format python uses for printing its stack traces, or would that sort of change require me to create a custom exception handler at the root of my program?


There is a means to change the format Python uses to format its stack traces, and that is that you write your own formatter instead. There is only one built-in format.

You can assign your own function to sys.excepthook and it will act as a top-level exception handler that will get access to exceptions that were about to rise uncaught and cause the program to exit. There you can make use of the traceback object to format things however you like. Triptych's answer shows how to use the traceback module to get the info for each stack frame. extract_tb returns a 4-tuple of the filename, line number, function, and source text of the offending line, so if you want to not display the source text you could just throw that away and concatenate the rest. But you'll have to do the work of constructing whatever output you want to see.


使用追溯模块

import traceback
try:
    x= 1/0
except Exception as e:
    print(e)
    traceback.print_exc()

If you really want to, you can reformat exception tracebacks with the traceback.extract_tb method.

ref: https://docs.python.org/2/library/traceback.html#traceback.extract_tb

链接地址: http://www.djcxy.com/p/82432.html

上一篇: Javascript异常堆栈跟踪

下一篇: 如何在Python中生成像堆栈跟踪的Java?