Reputation: 3882
I have code that can potentially have an endless loop. I would like to be able to stop this in code, is there somethng that can do that? Some thing like:
for i to range(0,5):
timer = on
run(x)
#while run is running
if timer.time > 30:
exit run(x)
print("out of time ")
print(timer.time)
So the output could be: 3, 2, out of time 30, 2, out of time 30
I'm afraid this might require threading, which I have attempted in C and Java, for school, but never python.
Upvotes: 2
Views: 402
Reputation: 179677
A few options:
run
's "endless" loop, make it check for the time. This is probably the easiest.signal.alarm
with a SIGALRM
handler to get interrupted after a fixed period of time.run
.run
into a separate process and kill the process when time expires (e.g. with multiprocessing
).Here's an example of interrupting a calculation using signal.alarm
:
import signal
class TimeoutException(Exception):
pass
def alarm_handler(*args):
raise TimeoutException()
def tryrun(func, timeout=30):
oldhandler = signal.signal(signal.SIGALRM, alarm_handler)
try:
signal.alarm(timeout)
func()
except TimeoutException:
print "Timeout"
else:
print "Success"
finally:
signal.alarm(0) # disarm alarm
signal.signal(signal.SIGALRM, oldhandler)
import time
tryrun(lambda: time.sleep(10), 5) # prints Timeout
tryrun(lambda: time.sleep(2), 5) # prints Success
Upvotes: 3