Question: Traceback information from sys.exc_info()

Donn Cave donn at u.washington.edu
Wed Aug 16 14:32:07 EDT 2000


Quoth "Brian Geddes" <brian.j.geddes at intel.com>:
| How do I get at the data in the traceback object returned by sys.exc_info()?
| I just need to get the name of the innermost function in the traceback, but
| I want to be able to use this information within the script.  I tried
| printing out the tuple returned by sys.exc_info(), but all I got was the
| memory address of the traceback object.  I am making sure to call
| sys.exc_info() while handling an exception, so I know I'm not dealing with
| an empty tuple.
|
| On a closely related subject, I'm also trying to figure out a way to get at
| the name of the current function being executed, while still inside of that
| function.  I know this information must be stored by the interpreter
| somewhere...I just don't know how to get at it.

Have a look at this and see if it's anywhere close.  As you surmised,
the questions are indeed closely related if my answer is any indication.
But tracebacks are relative to the handler, so this technique won't work
to make a function that returns the name of its caller, you have to
force the exception right there.  There may be another approach that
would support a more convenient whoami() function.

	Donn Cave, donn at u.washington.edu
----------------------------------------
import sys
import traceback

def a3():
    return Nought

def a2():
    try:
        a3()
    except:
        stack = traceback.extract_tb(sys.exc_traceback)
        file, line, func, stmt = stack[-1]
        print 'problem occured on line %s in function %s' % (line, func)
        print 'when you said %s' % (repr(stmt,))
    try:
        x = this_must_not_work
    except NameError:
        stack = traceback.extract_tb(sys.exc_traceback)
        file, line, func, stmt = stack[-1]                   # or 0
    print 'currently executing function %s' % (repr(func),)

def a1():
    a2()

a1()



More information about the Python-list mailing list