|
Re: getting values from an "exec" statement
|
Posted: Jun 16, 2004 10:56 AM
|
|
You can point standard output and standard error at a file-like string object, execute your code, then examine the captured strings:
import sys import StringIO # create file-like string to capture output codeOut = StringIO.StringIO() codeErr = StringIO.StringIO() code = """ for i in xrange(0,15): print i """ # capture output and errors sys.stdout = codeOut sys.stderr = codeErr exec code # restore stdout and stderr sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ s = codeErr.getvalue() if s: print "error:\n%s\n" % s s = codeOut.getvalue() if s: print "output:\n%s" % s codeOut.close() codeErr.close()
You can't time out code executed with the exec statement. You can wrap the above code in a function and execute it in a separate thread, but Python doesn't have any way for one thread to kill another. There is some commentary on that, and at least one threading library add-on that includes a kill function: use Google to search for "python kill thread" in Usenet.
Perhaps you can pre-process the code entered by the students and insert checkpoints inside loops and at other places, which will let the executed code check if it's supposed to terminate or not.
I thought about doing something like this -- allowing students to enter and execute Python code on a web page -- but decided it was too risky and hard to control. In the end my students installed Python on their own PCs and then uploaded their code for me and other students to look at.
Greg Jorgensen PDXperts LLC - Portland, Oregon USA
|
|