I want to timeout a particular piece of python code after in runs for 0.5 seconds. So I intend to raise an exception/signal after 0.5 seconds, and handle it gracefully and continue with rest of code.
In python i know that signal.alarm()
can set alarm for integer seconds. Is there any alternative where we can generate an alarm after 0.5 seconds. signal.setitimer()
as suggested in other posts is not available in python2.4 and I need to use python2.4 for this purpose?
To catch a signal in Python, you need to register the signal you want to listen for and specify what function should be called when that signal is received. This example shows how to catch a SIGINT and exit gracefully.
10 (SIGUSR1): user-defined signal. 11 (SIGSEGV): segmentation fault due to illegal access of a memory segment. 12 (SIGUSR2): user-defined signal. 13 (SIGPIPE): writing into a pipe, and nobody is reading from it. 14 (SIGALRM): the timer terminated (alarm)
signal. pause () Cause the process to sleep until a signal is received; the appropriate handler will then be called. Returns nothing. Availability: Unix.
Try calling signal. alarm(0) when you want to disable the alarm. In all likelyhood it just calls alarm() in libc, and the man alarm says that alarm(0) "... voids the current alarm and the signal SIGALRM will not be delivered."
Raise the alarm from a patiently waiting "daemon" thread. In the code below, snoozealarm
does what you want via a SnoozeAlarm
thread:
#! /usr/bin/env python
import os
import signal
import threading
import time
class SnoozeAlarm(threading.Thread):
def __init__(self, zzz):
threading.Thread.__init__(self)
self.setDaemon(True)
self.zzz = zzz
def run(self):
time.sleep(self.zzz)
os.kill(os.getpid(), signal.SIGALRM)
def snoozealarm(i):
SnoozeAlarm(i).start()
def main():
snoozealarm(0.5)
while True:
time.sleep(0.05)
print time.time()
if __name__ == '__main__':
main()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With