2017-10-20 87 views
1

我想运行某个函数foo并获取返回值,但前提是运行该函数的时间少于T秒。否则我会以None作为答案。python:使用超时运行函数(并获取返回值)

创建这种需求的具体用例是运行一系列经常挂起的sympy非线性求解器。在寻找sympy的帮助时,devs建议不要试图在sympy中这样做。但是,我找不到解决此问题的有用实施。

回答

0

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

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) 
+0

为什么不只是'thread.join(timeout)'而不是while循环? –

+0

如果超时设置为10秒,但该功能在1秒内完成,我认为没有while循环,您会被不必要地等待9秒钟。这样你可以更快地得到结果。纠正我,如果我错了。 – florisvb

+0

这是错误的'thread.join()'一旦超时用完或'线程'死亡(当它完成它的工作时会很快)就会返回。 –