Get Only the Last Items in a Traceback
gregpinero at gmail.com
gregpinero at gmail.com
Wed Sep 12 11:09:02 EDT 2007
On Sep 12, 5:17 am, Peter Otten <__pete... at web.de> wrote:
>
> Your assessment is wrong. You only get the extra lines in the traceback if
> you don't immediately wrap the exec statement in a try ... except block:
>
> $ cat snip_traceback1.py
> import traceback
>
> def alpha():
> try:
> beta()
> except Exception, e:
> traceback.print_exc()
>
> def beta():
> gamma()
>
> def gamma():
> exec s in {}
>
> s = """
> def delta():
> epsilon()
>
> def epsilon():
> 1/0
> delta()
> """
>
> if __name__ == "__main__":
> alpha()
>
> $ python snip_traceback1.py
> Traceback (most recent call last):
> File "snip_traceback1.py", line 5, in alpha
> beta()
> File "snip_traceback1.py", line 10, in beta
> gamma()
> File "snip_traceback1.py", line 13, in gamma
> exec s in {}
> File "<string>", line 7, in <module>
> File "<string>", line 3, in delta
> File "<string>", line 6, in epsilon
> ZeroDivisionError: integer division or modulo by zero
>
> So the first step is to move the try ... except closer to the exec:
>
> $ cat snip_traceback2.py
> import traceback
>
> def alpha():
> beta()
>
> def beta():
> gamma()
>
> def gamma():
> try:
> exec s in {}
> except Exception, e:
> traceback.print_exc()
>
> s = """
> def delta():
> epsilon()
>
> def epsilon():
> 1/0
> delta()
> """
>
> if __name__ == "__main__":
> alpha()
>
> $ python snip_traceback2.py
> Traceback (most recent call last):
> File "snip_traceback2.py", line 11, in gamma
> exec s in {}
> File "<string>", line 7, in <module>
> File "<string>", line 3, in delta
> File "<string>", line 6, in epsilon
> ZeroDivisionError: integer division or modulo by zero
>
> You are almost there. Now let's strip off the outermost traceback:
>
> $ cat snip_traceback3.py
> import sys
> import traceback
>
> def alpha():
> beta()
>
> def beta():
> gamma()
>
> def gamma():
> try:
> exec s in {}
> except Exception, e:
> etype, value, tb = sys.exc_info()
> traceback.print_exception(etype, value, tb.tb_next)
>
> s = """
> def delta():
> epsilon()
>
> def epsilon():
> 1/0
> delta()
> """
>
> if __name__ == "__main__":
> alpha()
>
> $ python snip_traceback3.py
> Traceback (most recent call last):
> File "<string>", line 7, in <module>
> File "<string>", line 3, in delta
> File "<string>", line 6, in epsilon
> ZeroDivisionError: integer division or modulo by zero
>
> Heureka.
>
> Peter
Thanks for the help, Peter. That's exactly what I need. Now could I
use your tb.tb_next trick a couple times and thus avoid moving the try/
except?
-Greg
More information about the Python-list
mailing list