2017-10-20 103 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()'一旦超時用完或'線程'死亡(當它完成它的工作時會很快)就會返回。 –