473,761 Members | 4,511 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

getting values from an "exec" statement

Hi all,

I'm designing an educational application that will run Python code and
check the output against a pre-define answer. I want to use the "exec"
statement to run the code, but I don't know how to get output from it.

For instance, exec works like this:
code = """ for i in xrange(1, 5):
print i
""" exec code

1
2
3
4

I want to store the values output by the print statement in a list. Is
there anyway to re-direct the output of the exec statement?

Also, it would be nice if exec had a timeout that automatically
haulted code that ran for too long. Is there a standard trick for
this? I expect I would have to run it in its own thread and kill the
thread when it takes too long (which reminds me I don't know anything
about Python threads!).

Toby
Jul 18 '05 #1
5 5780

"Toby Donaldson" <tj*@sfu.ca> wrote in message
news:ad******** *************** ***@posting.goo gle.com...
Hi all,

I'm designing an educational application that will run Python code and
check the output against a pre-define answer. I want to use the "exec"
statement to run the code, but I don't know how to get output from it.

For instance, exec works like this:
code = """ for i in xrange(1, 5):
print i
""" exec code

1
2
3
4

I want to store the values output by the print statement in a list. Is
there anyway to re-direct the output of the exec statement?


The code run by exec is run in the same scope as the exec (by default). So
anything done "in" the exec is visible to things "outside" the exec. Like
this:

l = []
code = """for i in xrange(1, 5):
l.append(i)"""
exec code
print l
greg
Jul 18 '05 #2
Python isn't really set up for what you're doing. The exec'd code can
too easily mess around with the calling code, if it's malicious.
You're best off just running the student's program in a separate
process and capturing the output.
Jul 18 '05 #3
Toby Donaldson wrote:
I'm designing an educational application that will run Python code and
check the output against a pre-define answer. I want to use the "exec"
statement to run the code, but I don't know how to get output from it.


Override sys.stdout with a proxy that will capture what's send to stdout
so you can do something with it. Of course, this won't help your second
problem -- trying to set up a useful sandbox -- but it's a start for
non-malicious code.

--
Erik Max Francis && ma*@alcyone.com && http://www.alcyone.com/max/
__ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
/ \ I am still learning.
\__/ (Michaelangelo' s motto)
Jul 18 '05 #4
Hello Toby,
I'm designing an educational application that will run Python code and
check the output against a pre-define answer. I want to use the "exec"
statement to run the code, but I don't know how to get output from it.

[...]

The battaries are there already...
http://www.python.org/doc/current/li...e-doctest.html

HTH.
Miki
Jul 18 '05 #5
Toby Donaldson wrote:
Hi all,

I'm designing an educational application that will run Python code and
check the output against a pre-define answer. I want to use the "exec"
statement to run the code, but I don't know how to get output from it.
I see you already received answers to this part.
I want to store the values output by the print statement in a list. Is
there anyway to re-direct the output of the exec statement?
I would suggest sys.stdout=cStr ingIO.StringIO( ) right before the
exec (and store it somewhere, and restore the previous value, in
a finally clause -- you DO want to have the exec inside a try
clause, of course, since it's so likely that exec will raise
exceptions!).

Also, it would be nice if exec had a timeout that automatically
haulted code that ran for too long. Is there a standard trick for
this? I expect I would have to run it in its own thread and kill the
thread when it takes too long (which reminds me I don't know anything
about Python threads!).


In Python 2.3, you can run the exec in the main thread after
setting up a secondary "watchdog" thread that calls function
thread.interrup t_main() after sleeping for a given length of
time; this will raise a KeyboardInterru pt in the main thread,
just as if somebody at the kbd had banged on Ctrl-C or the like.

Of course, this does NOT protect you against MALICIOUS code in
the exec -- THAT might easily capture and ignore the exception.
Your code will be MUCH more solid if you can arrange to execute
the untrusted code in a separate process (not hard on Linux,
BSD, and the like; possible -- though not quite as trivial -- on
Windows, too). But for "normal mistakes", it's reasonably OK.
Alex

Jul 18 '05 #6

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

Similar topics

2
4187
by: tedsuzman | last post by:
----- def f(): ret = 2 exec "ret += 10" return ret print f() ----- The above prints '12', as expected. However,
1
1692
by: Ted | last post by:
-------- def f(): ret = 2 exec "ret += 10" return ret print f() -------- The above example prints '12'. However, the following example prints
9
1634
by: Ximo | last post by:
Hello, I want that the return sentence don't return anything, how can I do it?. If i do only return it returns None, and pass don't run too. Can anyone help me?, thanks. XIMO
0
10211
by: Jan | last post by:
I store sql-commands in a database table. In the first step I get the sql command out of the database table with embedded sql. In the second step I try to execute the command, which i got from the database table, using dynamic sql. Executing 'EXEC SQL DESCRIBE SELECT LIST FOR S INTO select_dp;' the error code -2149 is returned That means "Specified partition does not exist". Does anybody know if it is a database problem or a problem of
10
5637
by: serge | last post by:
Using "SELECT * " is a bad practice even when using a VIEW instead of a table? I have some stored procedures that are identical with the difference of one statement in the WHERE clause. If I create a single View and specify also in this View the WHERE clause that is common in these stored procedures, I will have the new stored procecures changed to be like:
1
6508
by: laredotornado | last post by:
Hi, I'm using PHP 4.4.4 on Apache 2 on Fedora Core 5. PHP was installed using Apache's apxs and the php library was installed to /usr/local/php. However, when I set my "error_reporting" setting to be "E_ALL", notices are still not getting reported. The perms on my file are 664, with owner root and group root. The php.ini file is located at /usr/local/lib/php/php.ini. Any ideas why the setting does not seem to be having an effect? ...
21
7858
by: comp.lang.tcl | last post by:
set php {<? print_r("Hello World"); ?>} puts $php; # PRINTS OUT <? print_r("Hello World"); ?> puts When I try this within TCL I get the following error:
0
3984
by: jeoffh | last post by:
Background: I am trying to "merge" some attributes into an existing XML column in my MS SQL 2005 database. The general idea is that I have an XML column in a table and I would like to update/delete some values while leaving the other values alone. I am designing this database/table/column so maybe I could use attributes or elements/nodes, the choice is ultimately mine. The one constraint is that I have to allow for customized name/value pairs....
4
3159
by: Gilles Ganault | last post by:
Hello I'm puzzled as to why PHP (5) prints this (under FreeBSD 6.3): ========= #!/usr/local/bin/php <?php $dbh = new PDO("sqlite:test.sqlite"); $sql = "CREATE TABLE IF NOT EXISTS calls (calls_id INTEGER PRIMARY
0
10136
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
9989
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
9925
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
9811
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7358
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5405
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3913
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
3
3509
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2788
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.