Question

how to time-out a statement/block of code in python?

I tried using the below looking at a post but it couldn't identify the signal:

wls:/offline> import signal

Traceback (innermost last):

  File "<console>", line 1, in ?

ImportError: no module named signal

code:

import os
import signal

def handler(signum, frame):
    print "Forever is over!"    
    raise Exception("end of time")

def loop_forever():
    import time
    while 1:
        print "sec"
        time.sleep(1)

signal.signal(signal.SIGALRM, handler)
signal.alarm(10)

try:
    loop_forever()
except Exception, exc:
    print exc
Was it helpful?

Solution 2

This seems to be working

Which calls a method after the timeout:

from threading import Timer

import time


def timeout():

    print 'in timeout'


def main():

    print 'it keeps going and going ',

    while 1:

        print 'and going '

        time.sleep(3)


try:

    Timer(5.0,timeout).start()

    main()

except:

    print "whoops"

OTHER TIPS

Your code is working perfectly well for me:

>>> import os
>>> import signal
>>> 
>>> def handler(signum, frame):
...     print "Forever is over!"    
...     raise Exception("end of time")
... 
>>> def loop_forever():
...     import time
...     while 1:
...         print "sec"
...         time.sleep(1)
... 
>>> signal.signal(signal.SIGALRM, handler)
0
>>> signal.alarm(10)
0
>>> 
>>> try:
...     loop_forever()
... except Exception, exc:
...     print exc
... 
sec
sec
sec
sec
sec
sec
sec
sec
sec
sec
Forever is over!
end of time

Though, are you using a Unix system to try this? Whether this is a Linux, a BSD or a Mac? The signal module may not be present at all on other OS, as this is using a feature very specific to unix systems, even though windows does have a very basic support of POSIX processes.

edit: Well, as I'm saying you're in a very particular case, which is neither Unix or windows or even symbian ; but you're running it in Jython, which does not have access to the OS features, whereas the lack of signal module. You should have tagged your question with Jython, to help us help you more efficiently! Then you'd better use a thread timer which should be well implemented in Jython.

As a very basic example:

 >>> threading.Timer(5.0, lambda: print("toto")).start()

As a more complex example, where I'm using a simple lock semaphore to handle the signaling between the main thread and the timer thread:

>>> import time
>>> import threading
>>> l = threading.Lock()
>>> threading.Timer(5.0, lambda l: l.acquire(), args=(l,)).start()
>>> while not l.locked():
...   print("sec")
...   time.sleep(1)
... 
sec
sec
sec
sec
sec
>>> 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top