2

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.

4

1 回答 1

3

A few options:

  1. If you can modify run's "endless" loop, make it check for the time. This is probably the easiest.
  2. If on Linux/UNIX, you can use signal.alarm with a SIGALRM handler to get interrupted after a fixed period of time.
  3. You can spawn a separate thread and kill the other thread when time elapses. This is rather nasty, and should only be used if you're on Windows (or care about portability) and have no way to modify run.
  4. You could spawn 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
于 2013-03-30T19:29:20.737 回答