python:运行带有超时的函数(并获取返回值)
我想运行一些函数foo并获取返回值,但前提是运行该函数所需的时间少于T秒。否则我就什么也不做了python:运行带有超时的函数(并获取返回值),python,function,timeout,Python,Function,Timeout,我想运行一些函数foo并获取返回值,但前提是运行该函数所需的时间少于T秒。否则我就什么也不做了 对我来说,产生这种需求的具体用例是运行一系列Symphy非线性解算器,这些解算器经常挂起。在搜索Symphy的帮助时,开发人员建议不要在Symphy中尝试这样做。但是,我找不到一个有用的实现来解决这个问题。这就是我最后要做的。如果您有更好的解决方案,请分享 import threading import time # my function that I want to run with a tim
对我来说,产生这种需求的具体用例是运行一系列Symphy非线性解算器,这些解算器经常挂起。在搜索Symphy的帮助时,开发人员建议不要在Symphy中尝试这样做。但是,我找不到一个有用的实现来解决这个问题。这就是我最后要做的。如果您有更好的解决方案,请分享
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
死亡时返回(在它完成工作时发生)。只需检查我自己和您是否正确,这就简化了事情。将更新答案。谢谢