【问题标题】:python: run a function with a timeout (and get a returned value)python:运行一个超时的函数(并获得一个返回值)
【发布时间】:2017-10-20 23:11:06
【问题描述】:

我想运行某个函数 foo 并获取返回值,但前提是运行该函数所需的时间少于 T 秒。否则,我将无作为答案。

为我创造了这种需求的具体用例是运行一系列 sympy 非线性求解器,这些求解器经常挂起。在搜索 sympy 的帮助时,开发人员建议不要尝试在 sympy 中这样做。但是,我找不到解决此问题的有用实现。

【问题讨论】:

    标签: python function timeout


    【解决方案1】:

    这就是我最终要做的。如果您有更好的解决方案,请分享!

    import threading
    import time
    
    # my function that I want to run with a timeout
    def foo(val1, val2):
        time.sleep(5)
        return val1+val2
    
    class RunWithTimeout(object):
        def __init__(self, function, args):
            self.function = function
            self.args = args
            self.answer = None
    
        def worker(self):
            self.answer = self.function(*self.args)
    
        def run(self, timeout):
            thread = threading.Thread(target=self.worker)
            thread.start()
            thread.join(timeout)
            return self.answer
    
    # this takes about 5 seconds to run before printing the answer (8)
    n = RunWithTimeout(foo, (5,3))
    print n.run(10)
    
    # this takes about 1 second to run before yielding None
    n = RunWithTimeout(foo, (5,3))
    print n.run(1)
    

    【讨论】:

    • 为什么不只是thread.join(timeout) 而不是while循环?
    • 如果超时设置为 10 秒,但函数在 1 秒内完成,我认为如果没有 while 循环,您将不必要地等待 9 秒。这样,您可以更快地获得结果。如果我错了,请纠正我..
    • 这是错误的,thread.join() 在超时结束或thread 死亡时立即返回(当它完成工作时会发生这种情况)。
    • 刚刚检查了自己,您是正确的,这简化了事情。将更新答案。谢谢!
    猜你喜欢
    • 2017-07-11
    • 2022-10-14
    • 2018-12-04
    • 1970-01-01
    • 2018-09-11
    • 2016-10-27
    • 1970-01-01
    • 2020-03-05
    • 1970-01-01
    相关资源
    最近更新 更多