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

Viewed 420

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?

2 Answers

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]

sys.excepthook lets you specify a function to print out to stderr and use traceback.format_tb to parse the traceback. The benefit being here you don't have to catch the error from a try ... except.

import sys
import traceback as tb

def except_hook(type, value, traceback):
    lines = 10
    tb_lines = "".join(tb.format_tb(traceback)).split("\n")
    print("\n".join(tb_lines[-lines:] + [repr(value)]), file=sys.stderr)

sys.excepthook = except_hook

def a(x):
    return b(x)

def b(x):
    return c(x)

def c(x):
    return d(x)

def d(x):
    return x / 0

a(5)

Which produces:

~ python err.py
    a(5)
  File "err.py", line 12, in a
    return b(x)
  File "err.py", line 15, in b
    return c(x)
  File "err.py", line 18, in c
    return d(x)
  File "err.py", line 21, in d
    return x / 0

ZeroDivisionError('division by zero')
Related