0

I need to apply a function several times on different inputs. Sometimes the function takes hours to run. I do not want it to last more than 10 seconds. I found the method on a previous post (How to limit execution time of a function call in Python). I can use it but as soon as it's done my kernel dies (unexpectedly). You'll find bellow an example.

Does someone face this problem / know why it happens ?

Fyk: I use spider (Python 2.7.11 64bits, Qt 4.8.7, PyQt4 (API v2) 4.11.4 on Darwin)

import signal
import time


def signal_handler(signum, frame):
    raise Exception("Timed out!")

for i in range(10):
    signal.signal(signal.SIGALRM, signal_handler)
    signal.alarm(10)   # Ten seconds
    try:
        time.sleep(0.2) #  The function I want to apply
        print("Ok it works")
    except Exception, msg:
        print "Timed out!"
Community
  • 1
  • 1
Jb_Eyd
  • 635
  • 1
  • 7
  • 20

1 Answers1

1

You're creating 10 signals with SIGALRM handler, meaning you now have 10 exceptions going on at the same time. You may want to instead try:

signal.signal(signal.SIGALRM, signal_handler)
signal.alarm(10)   # Ten seconds

for i in range(10):
    try:
        time.sleep(0.2) #  The function I want to apply
        print("Ok it works")
    except Exception, msg:
        print "Timed out!"
        break

Or you might want to consider closing the alarm after the signal should be complete:

for i in range(10):
    signal.signal(signal.SIGALRM, signal_handler)
    signal.alarm(10)   # Ten seconds
    try:
        time.sleep(i * 2) #  Force it to break,
        print("Ok it works")
    except Exception, msg:
        print "Timed out!"
    signal.alarm(0)
cwallenpoole
  • 79,954
  • 26
  • 128
  • 166
  • Tks for your answer. I didn't realise that I needed to close my signal.alarm ! I want the alarm inside the loop though. But if I close it, it works ! – Jb_Eyd Jul 13 '16 at 15:18