473,656 Members | 2,793 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Get Only the Last Items in a Traceback

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()

Which gives me something like this when it catches an exception:

Traceback (most recent call last):
File "/....py", line 843, in run
semi_safe_exec. safe_eval(code. replace('\r','' ),context,5)
File ".....py", line 400, in safe_eval
exec_timed(code , context, timeout_secs)
File ".....py", line 353, in exec_timed
exec code in context
File "<string>", line 7, in ?
File "<string>", line 5, in func2
File "<string>", line 2, in func1
ZeroDivisionErr or: integer division or modulo by zero

What I want to print instead is just something like:

Traceback (most recent call last):
File "<string>", line 7, in ?
File "<string>", line 5, in func2
File "<string>", line 2, in func1
ZeroDivisionErr or: integer division or modulo by zero

Thanks in advance for the help.

-Greg

P.S. if it matters, for this example, code in exec code is:

def func1():
print 7/0

def func2():
func1()

func2()

Sep 12 '07 #1
8 1995
Am Wed, 12 Sep 2007 02:09:28 +0000 schrieb gr********@gmai l.com:
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()

Which gives me something like this when it catches an exception:

Traceback (most recent call last):
File "/....py", line 843, in run
semi_safe_exec. safe_eval(code. replace('\r','' ),context,5)
File ".....py", line 400, in safe_eval
exec_timed(code , context, timeout_secs)
File ".....py", line 353, in exec_timed
exec code in context
File "<string>", line 7, in ?
File "<string>", line 5, in func2
File "<string>", line 2, in func1
ZeroDivisionErr or: integer division or modulo by zero

What I want to print instead is just something like:

Traceback (most recent call last):
File "<string>", line 7, in ?
File "<string>", line 5, in func2
File "<string>", line 2, in func1
ZeroDivisionErr or: integer division or modulo by zero

Thanks in advance for the help.

-Greg

P.S. if it matters, for this example, code in exec code is:

def func1():
print 7/0

def func2():
func1()

func2()
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_traceback 1.py", line 5, in alpha
beta()
File "snip_traceback 1.py", line 10, in beta
gamma()
File "snip_traceback 1.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
ZeroDivisionErr or: 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_traceback 2.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
ZeroDivisionErr or: 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(etyp e, 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
ZeroDivisionErr or: integer division or modulo by zero

Heureka.

Peter
Sep 12 '07 #2
gr********@gmai l.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:

-------------------------------- snip --------------------------------
print_exc( [limit[, file]])
This is a shorthand for print_exception (sys.exc_type, sys.exc_value,
sys.exc_traceba ck, limit, file). (In fact, it uses sys.exc_info() to
retrieve the same information in a thread-safe way instead of using the
deprecated variables.)
-------------------------------- snip --------------------------------

Ciao, Michael.
Sep 12 '07 #3
Am Wed, 12 Sep 2007 11:21:48 +0200 schrieb Michael Ströder:
gr********@gmai l.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
ZeroDivisionErr or: 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>
ZeroDivisionErr or: integer division or modulo by zero
>>>
Peter
Sep 12 '07 #4
On Sep 12, 5:17 am, Peter Otten <__pete...@web. dewrote:
>
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_traceback 1.py", line 5, in alpha
beta()
File "snip_traceback 1.py", line 10, in beta
gamma()
File "snip_traceback 1.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
ZeroDivisionErr or: 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_traceback 2.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
ZeroDivisionErr or: 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(etyp e, 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
ZeroDivisionErr or: 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

Sep 12 '07 #5
Am Wed, 12 Sep 2007 15:09:02 +0000 schrieb gr********@gmai l.com:
On Sep 12, 5:17 am, Peter Otten <__pete...@web. dewrote:
>>
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_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(etyp e, 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
ZeroDivisionEr ror: integer division or modulo by zero

Heureka.
Thanks for the help, Peter. That's exactly what I need.
Indeed. But not exactly what you want, it seems.
Now could I
use your tb.tb_next trick a couple times and thus avoid moving the try/
except?
Of course you can cut off the traceback at arbitrary positions. Here's an
example that uses the filename:

import traceback
import sys

def tb_filename(tb) :
return tb.tb_frame.f_c ode.co_filename

def tb_iter(tb):
while tb is not None:
yield tb
tb = tb.tb_next

def alpha():
try:
beta()
except Exception, e:
etype, value, tb = sys.exc_info()
filename = tb_filename(tb)
for tb in tb_iter(tb):
if tb_filename(tb) != filename:
break
traceback.print _exception(etyp e, value, tb)

def beta():
gamma()

def gamma():
exec s in {}

s = """
def delta():
epsilon()

def epsilon():
1/0
delta()
"""

if __name__ == "__main__":
alpha()

Did I mention it already? It's better to move the try ... except.

Peter
Sep 12 '07 #6
On Sep 12, 11:35 am, Peter Otten <__pete...@web. dewrote:
Am Wed, 12 Sep 2007 15:09:02 +0000 schrieb gregpin...@gmai l.com:
On Sep 12, 5:17 am, Peter Otten <__pete...@web. dewrote:
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_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(etyp e, 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
ZeroDivisionErr or: integer division or modulo by zero
Heureka.
Thanks for the help, Peter. That's exactly what I need.

Indeed. But not exactly what you want, it seems.
Now could I
use your tb.tb_next trick a couple times and thus avoid moving the try/
except?

Of course you can cut off the traceback at arbitrary positions. Here's an
example that uses the filename:

import traceback
import sys

def tb_filename(tb) :
return tb.tb_frame.f_c ode.co_filename

def tb_iter(tb):
while tb is not None:
yield tb
tb = tb.tb_next

def alpha():
try:
beta()
except Exception, e:
etype, value, tb = sys.exc_info()
filename = tb_filename(tb)
for tb in tb_iter(tb):
if tb_filename(tb) != filename:
break
traceback.print _exception(etyp e, value, tb)

def beta():
gamma()

def gamma():
exec s in {}

s = """
def delta():
epsilon()

def epsilon():
1/0
delta()
"""

if __name__ == "__main__":
alpha()

Did I mention it already? It's better to move the try ... except.

Peter

This approach is ideal. Indirect, but ideal :-) I'll apply it
tonight.

It's complicated but suffice it to say it would be difficult to move
the try/except. Thanks for the help. Way to know about tracebacks,
very impressive!

-Greg

Sep 12 '07 #7
On Sep 12, 10:35 am, Peter Otten <__pete...@web. dewrote:
Am Wed, 12 Sep 2007 15:09:02 +0000 schrieb gregpin...@gmai l.com:
On Sep 12, 5:17 am, Peter Otten <__pete...@web. dewrote:
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_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(etyp e, 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
ZeroDivisionErr or: integer division or modulo by zero
Heureka.
Thanks for the help, Peter. That's exactly what I need.

Indeed. But not exactly what you want, it seems.
Now could I
use your tb.tb_next trick a couple times and thus avoid moving the try/
except?

Of course you can cut off the traceback at arbitrary positions. Here's an
example that uses the filename:

import traceback
import sys

def tb_filename(tb) :
return tb.tb_frame.f_c ode.co_filename

def tb_iter(tb):
while tb is not None:
yield tb
tb = tb.tb_next

def alpha():
try:
beta()
except Exception, e:
etype, value, tb = sys.exc_info()
filename = tb_filename(tb)
for tb in tb_iter(tb):
if tb_filename(tb) != filename:
break
traceback.print _exception(etyp e, value, tb)

def beta():
gamma()

def gamma():
exec s in {}

s = """
def delta():
epsilon()

def epsilon():
1/0
delta()
"""

if __name__ == "__main__":
alpha()

Did I mention it already? It's better to move the try ... except.

Peter
This works great except for syntax errors. Any idea why your solution
doesn't catch those?

Here's the output it gives me, followed by the code I'm using (running
in Python 2.5):

Traceback (most recent call last):
File "traceback_test .py", line 27, in gamma
exec s in {}
File "<string>", line 6
print hi'
^
SyntaxError: EOL while scanning single-quoted string
file traceback_test. py contents:
import traceback
import sys

def tb_filename(tb) :
return tb.tb_frame.f_c ode.co_filename

def tb_iter(tb):
while tb is not None:
yield tb
tb = tb.tb_next

def alpha():
try:
beta()
except Exception, e:
etype, value, tb = sys.exc_info()
filename = tb_filename(tb)
for tb in tb_iter(tb):
if tb_filename(tb) != filename:
break
traceback.print _exception(etyp e, value, tb)

def beta():
gamma()

def gamma():
exec s in {}

s = """
def delta():
epsilon()

def epsilon():
print hi'
delta()
"""

if __name__ == "__main__":
alpha()

-Greg

Nov 7 '07 #8
En Wed, 07 Nov 2007 01:53:31 -0300, gr********@gmai l.com
<gr********@gma il.comescribió:
This works great except for syntax errors. Any idea why your solution
doesn't catch those?

Here's the output it gives me, followed by the code I'm using (running
in Python 2.5):

Traceback (most recent call last):
File "traceback_test .py", line 27, in gamma
exec s in {}
File "<string>", line 6
print hi'
^
SyntaxError: EOL while scanning single-quoted string
Which would be your expected output?
Syntax errors happen when the code is *compiled*, before it gets executed.
You may catch syntax errors before even trying to execute the code, if you
do it in two steps:

try:
ccode = compile(s, filename, 'exec')
except SyntaxError:
...show the error appropiately...
...abort execution...
try:
exec ccode in {}
except Exception, e:
...handle exception...
--
Gabriel Genellina

Nov 10 '07 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
2421
by: Doug Farrell | last post by:
Hi everyone, I'm trying to build a program to interface to a SOAP/XML interface provided by one of our vendors. This interface is built with MS SOAP Toolkit 3.0, so I'm guessig they are running a .NET server. I'm trying to build my program with Python as I've got to deploy on both Linux and Sun/Solaris platforms. I'm developing on RedHat Linux 8.0 using Python 2.2.1 and SOAPpy 0.10.2. My experimental program almost works, but it isn't...
0
1030
by: Christian Tismer | last post by:
Dear Python community, since I didn't get *any* reply to this request, either the request was bad or there is really nobody using f_tstate in a way that makes it urgent to keep. I will wait a few hours and then make the change to Stackless, and I'd like to propose to do the same to the Python core.
11
2186
by: Vani Murarka | last post by:
Hi Everyone, Does .NET offer any collection class which will give me objects last *accessed* such that I may build a least-recently-used cache that kills off objects that haven't been used for awhile? Or is there any other way to implement this kind of a cache / collection where one can do this kind of cleanup based on least-recently-used objects?
32
4127
by: James Curran | last post by:
I'd like to make the following proposal for a new feature for the C# language. I have no connection with the C# team at Microsoft. I'm posting it here to gather input to refine it, in an "open Source" manner, and in an attempt to build a ground-swell of support to convince the folks at Microsoft to add it. Proposal: "first:" "last:" sections in a "foreach" block The problem: The foreach statement allows iterating over all the...
3
3308
by: Guoqi Zheng | last post by:
Sir, According to our design, very often, I need to have a different html code for the last row of our repeater control. I can not put those code difference into footer because those code has to be in the last data row. How can I edit the last data row of a repeater control?? -- Kind regards
5
3734
by: Nathan Sokalski | last post by:
I have a control that I want displayed in all items except the last one. I figured the best way to do this was to determine whether the current item was the last from within the ItemDataBound event using code such as the following: If e.Item.ItemIndex=(numberofitems-1) Then mycontrol.Enabled=False but I cannot find a property that contains the total number of items before
1
3547
by: Kimmo Laine | last post by:
Hi! I need to resize the last column in my listview control so that there won´t be horizontal scrollbar. Lets first create lv and add some items: listView1.View = View.Details;
23
18059
by: Florian Lindner | last post by:
Hello, can I determine somehow if the iteration on a list of values is the last iteration? Example: for i in : if last_iteration: print i*i else:
3
1382
by: Koen Vossen | last post by:
A project I'm currently working on uses Turbogears as a framework. I'd like to interact with it using the tg-admin shell. We also use gettext's _() function for internationalization. Now, this function is overwritten in interactive mode, which causes annoying exceptions. Is it possible to disable this behavior?
0
8297
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8816
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8717
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8498
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7311
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4150
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2726
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
1930
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1600
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.