signal.alarm replacement in Windows [Python] signal.alarm replacement in Windows [Python] python python

signal.alarm replacement in Windows [Python]


The most robust solution is to use a subprocess, then kill that subprocess. Python2.6 adds .kill() to subprocess.Popen().

I don't think your threading approach works as you expect. Deleting your reference to the Thread object won't kill the thread. Instead, you'd need to set an attribute that the thread checks once it wakes up.


Here's how the original poster solved his own problem:

Ended up going with a thread. Only trick was using os._exit instead of sys.exit

import osimport timeimport threadingclass Alarm (threading.Thread):    def __init__ (self, timeout):        threading.Thread.__init__ (self)        self.timeout = timeout        self.setDaemon (True)    def run (self):        time.sleep (self.timeout)        os._exit (1)alarm = Alarm (4)alarm.start ()time.sleep (2)del alarmprint 'yup'alarm = Alarm (4)alarm.start ()time.sleep (8)del alarmprint 'nope'  # we don't make it this far


You could - as you mentioned - just kick off a new thread that sleeps for that number of seconds.

Or you can use one of Windows' multimedia timers (in Python, that'd be in windll.winmm). I believe timeSetEvent is what you're looking for. Incidentally, I found a piece of code that uses it here.