Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you programmatically inspect the stack trace of an exception in Python?

When an exception occurs in Python, can you inspect the stack? Can you determine its depth? I've looked at the traceback module, but I can't figure out how to use it.

My goal is to catch any exceptions that occur during the parsing of an eval expression, without catching exceptions thrown by any functions it may have called. Don't berate me for using eval. It wasn't my decision.

NOTE: I want to do this programmatically, not interactively.

like image 858
Nick Retallack Avatar asked Mar 01 '10 21:03

Nick Retallack


1 Answers

traceback is enough - and I suppose that documentation describes it rather well. Simplified example:

import sys
import traceback

try:
    eval('a')
except NameError:
    traceback.print_exc(file=sys.stdout)
like image 191
Dmitry Kochkin Avatar answered Oct 11 '22 18:10

Dmitry Kochkin