Python exception: how to print the last ten lines of stack trace?

rwallace :

In Python as many other languages, the default behavior of an uncaught exception is to print a full stack trace. This is useful except that hundreds of lines of stack trace obscure previous console output with data most of which is uninformative. I really just want to see maybe the last ten lines of the stack trace.

What code can go into an exception handler to print a stack trace just the way it would happen with an uncaught exception, except only print the last ten lines?

Wasif Hasan :

Try this:

# import trace back module and get stack trace
import traceback 
try:
  statement
except:
  error = traceback.format_exc()

# split stack trace into a list and slice it
stack_trace = error.split('\n')
stack_trace[len(stack_trace)-10:len(stack_trace)+1]

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=394749&siteId=1