Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to signal alarm in python 2.4 after 0.5 seconds

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?

like image 604
Nithin Lingala Avatar asked Nov 23 '11 12:11

Nithin Lingala


People also ask

How do you catch signals in Python?

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.

What is SIGUSR1 in Python?

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)

What is signal pause?

signal. pause () Cause the process to sleep until a signal is received; the appropriate handler will then be called. Returns nothing. Availability: Unix.

How do you disable a signal alarm in Python?

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."


1 Answers

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()
like image 179
pilcrow Avatar answered Nov 15 '22 16:11

pilcrow