我想运行某个函数,foo,并获取返回值,但前提是运行函数所需的时间少于T秒。否则我会以无作为答案。
为我创造这种需求的特定用例是运行一系列经常挂起的 sympy 非线性求解器。在搜索 sympy 帮助时,开发人员建议不要尝试在 sympy 中这样做。但是,我找不到解决此问题的有用实现。
这就是我最终所做的。如果您有更好的解决方案,请分享!
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)