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 u开发者_运维问答se 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.
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).
This is just a guess, but maybe wrap it with Threading or Multiprocessing? Have a timer thread that kills it when it times out.
精彩评论