473,387 Members | 1,528 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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 5759

"Toby Donaldson" <tj*@sfu.ca> wrote in message
news:ad**************************@posting.google.c om...
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=cStringIO.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.interrupt_main() after sleeping for a given length of
time; this will raise a KeyboardInterrupt 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
by: tedsuzman | last post by:
----- def f(): ret = 2 exec "ret += 10" return ret print f() ----- The above prints '12', as expected. However,
1
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
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
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...
10
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...
1
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"...
21
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
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...
4
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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...

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.