getting values from an "exec" statement

Alex Martelli aleax at aleax.it
Wed Oct 1 08:00:33 EDT 2003


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





More information about the Python-list mailing list