在 Python 中限制函数调用的执行时间会杀死我的内核

Limiting execution time of a function call in Python kills my Kernel

我需要在不同的输入上多次应用一个函数。有时函数需要数小时才能 运行。我不希望它持续超过 10 秒。我在之前的一篇post(How to limit execution time of a function call in Python)上找到了方法。我可以使用它,但一旦它完成我的内核就死了(意外地)。你会在下面找到一个例子。

有人遇到过这个问题/知道为什么会这样吗?

Fyk:我在 Darwin 上使用 spider(Python 2.7.11 64 位,Qt 4.8.7,PyQt4(API v2)4.11.4)

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

您正在使用 SIGALRM 处理程序创建 10 个信号,这意味着您现在有 10 个异常同时发生。您可能想改为尝试:

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

或者您可能想考虑在信号完成后关闭警报:

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)