[Tutor] Exceptions: Logging TB and local variables?

Kalle Svensson kalle.svensson at gmail.com
Wed Oct 10 09:52:55 CEST 2007


On 10/10/07, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> "Allen Fowler" <allen.fowler at yahoo.com> wrote
>
> > Now, I would like to do this:
> >
> > for item in bigset:
> >   try:
> >     self.__sub1(item)
> >     self.__sub2(item)
> >     self.__sub3(item)
> >   except StandardError:
> >     # Log error and continue to next item in set.
> >     log_error_to_file()
> >
> > In the error log, I would like to record a stacktrace and various
> > local variables that existed in subX at the time the Exception
> > was thrown...
>
> Look at the traceback module.
> It was discussed in a recent thread - A Simple question - starting
> on October 2nd...
>
> > (even though the actual exception may have been thrown from
> > deep inside some 3rd party module that subX called)
>
> Examining data at the time of an exception is easy enough
> but only if the data is in scope. If it is local data within the
> raising function then bit will be gone by the time you catch
> the exception.

Well, not entirely. If you look at the sys.exc_info() function there
is a way to get the
backtrace of the currently handled exception. Using this, you can get
to the locals:

>>> def a(x):
...     l = 0
...     print x/l
...
>>> def b(y):
...     c = 75
...     a(y)
...
>>> try:
...     b(3)
... except:
...     t,v,bt = sys.exc_info()
...
>>> bt
<traceback object at 0xb7dafcac>
>>> dir(bt)
['tb_frame', 'tb_lasti', 'tb_lineno', 'tb_next']
>>> bt.tb_next.tb_frame.f_locals
{'y': 3, 'c': 75}
>>> bt.tb_next.tb_next.tb_frame.f_locals
{'x': 3, 'l': 0}
>>> del bt

Read more about backtrace and frame objects on:
http://www.python.org/doc/ref/types.html
http://www.python.org/doc/lib/module-sys.html

Also note the warnings in the sys.exc_info documentation.

Regards,
  Kalle


More information about the Tutor mailing list