views:

164

answers:

2

The user is entering a python script in a Java GUI python-editor and can run it from the editor. Is there a way to take the user's script and impose a time limit on the total script?

I'm familiar with how to this with functions / signal.alarm(but I'm on windows & unix Jython) but the only solution I have come up with is to put that script in a method in another script where I use the setTrace() function but that removes the "feature" that the value of global variables in it persist. ie.

try:
 i+=1
except NameError:
 i=0

The value of 'i' increments by 1 with every execution.

A: 

This is just a guess, but maybe wrap it with Threading or Multiprocessing? Have a timer thread that kills it when it times out.

Brian C. Lane
+3  A: 

Use a threading.Timer to run a function in a separate thread after a specified delay (the max duration you want for your program), and in that function use thread.interrupt_main (note it's in module thread, not in module threading!) to raise a KeyboardInterrupt exception in the main thread.

A more solid approach (in case the script gets wedged into some non-interruptible non-Python code, so that it would ignore keyboard interrupts) is to spawn a "watchdog process" to kill the errant script very forcefully if needed (do that as well as the above approach, and a little while later than the delay you use above, to give the script a chance to run its destructors, atexit functions, etc, if at all feasible).

Alex Martelli
thanks! I'm not an advanced python user but I'm going to try to get this working.
Leonidas
ah I'm using Jython 2.1 so thread.interrupt_main() doesn't work!
Leonidas
@Leonidas, I don't know for sure how a Java or Jython thread can best interrupt (cleanly, i.e., with all finalizers and try/finally's running, etc) the whole process. What about java.lang.System.exit(1)...?
Alex Martelli