Leonidas
Leonidas

Reputation: 2160

How to impose a time limit on a whole script in Python

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.

Upvotes: 0

Views: 2532

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 881655

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).

Upvotes: 4

Brian C. Lane
Brian C. Lane

Reputation: 4171

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

Upvotes: 0

Related Questions