Get Only the Last Items in a Traceback

Peter Otten __peter__ at web.de
Wed Sep 12 07:56:22 EDT 2007


Am Wed, 12 Sep 2007 11:21:48 +0200 schrieb Michael Ströder:

> gregpinero at gmail.com wrote:
>> I'm running code via the "exec in context" statement within a much
>> larger program.  What I would like to do is capture any possible
>> errors and show a pretty traceback just like the Python interactive
>> interpreter does, but only show the part of the traceback relating to
>> the code sent to exec.
>> 
>> For example here is the code I'm using:
>> 
>> try:
>>     exec code
>> except Exception,Err:
>>     traceback.print_exc()
> 
> Guess what's argument limit is for. Excerpt from the Python docs:

Unfortunately traceback.print_exc(limit=N) trims the wrong end of the
traceback:

>>> def alpha(): beta()
... 
>>> def beta(): gamma()
... 
>>> def gamma(): 1/0
... 
>>> try:
...     alpha()
... except:
...     traceback.print_exc()
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "<stdin>", line 1, in alpha
  File "<stdin>", line 1, in beta
  File "<stdin>", line 1, in gamma
ZeroDivisionError: integer division or modulo by zero
>>> try:
...     alpha()
... except:
...     traceback.print_exc(limit=1)
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero
>>>

Peter



More information about the Python-list mailing list