Deeper tracebacks?

brooklineTom BrooklineTom at gmail.com
Thu Dec 11 18:26:11 CET 2008


BINGO! Give that man a CIGAR!

The specifics don't seem to be quite right (there is no
sys.last_traceback), but R.Bernstein put me directly on the correct
track. I misunderstood the traceback module documentation. OK, I just
plain didn't read it correctly, it's right there ("extract_stack():
Extract the raw traceback from the current stack frame."). The answer
is to use traceback.extract_tb (), called with sys.exc_info()[3] (the
stackframe that raised the exception).

Another sterling example of the benefits of reading the fine manual --
for comprehension this time.

Instead of:
    aRawStack = traceback.extract_stack()
do this:
    aRawStack = traceback.extract_tb(sys.exc_info()[2])

With this change, aRawStack contains the following:

>>> aRawStack[0][3]
'answer = apply(aMethod, [], {})'
>>> aRawStack[1][3]
'int(3).zork()'

This is *exactly* what I was seeking.

I appreciate all the responses, and especially appreciate the pointer
from R.Bernstein.

Thx,
Tom

On Dec 11, 4:49 am, ro... at panix.com (R. Bernstein) wrote:
> brooklineTom <Brookline... at gmail.com> writes:
> > I want my exception handler to report the method that originally
> > raised an exception, at the deepest level in the call-tree. Let give
> > an example.
>
> > import sys, traceback
> > class SomeClass:
> >     def error(self):
> >         """Raises an AttributeError exception."""
> >         int(3).zork()
>
> >     def perform_(self, aSelector):
> >         try:
> >             aMethod = getattr(self, aSelector, None)
> >             answer = apply(aMethod, [], {})
> >         except: AttributeError, anAttributeErrorException:
> >             aRawStack = traceback.extract_stack()
> >             answer = None
>
> > When I call "perform_" (... SomeClass().perform_('error')), I want to
> > collect and report the location *within the method ("error") that
> > failed*. The above code reports the location of "perform_", and no
> > deeper in the call tree.
>
> > Anybody know how to accomplish this?
>
> extract_stack() without any arguments is getting this from the
> *current frame* which as you noted doesn't have the last exception
> info included which has been popped; variable sys.last_traceback has the frames
> at the time of the exception, I think.
>
> So in your code try changing:
>              aRawStack = traceback.extract_stack()
> to
>              aRawStack = traceback.extract_stack(sys.last_traceback)



More information about the Python-list mailing list