Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: run a function with a timeout (and get a returned value) [duplicate]

I want to run some function, foo, and get the return value, but only if it take less than T seconds to run the function. Otherwise I'll take None as an answer.

The specific use case that created this need for me, is in running a series of sympy nonlinear solvers, which often hang. In searching the help for sympy, devs recommended not trying to do that in sympy. But, I could not find a helpful implementation that solved this problem.

like image 487
florisvb Avatar asked May 16 '26 21:05

florisvb


1 Answers

This is what I ended up doing. If you have a better solution, please share!

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)
like image 103
florisvb Avatar answered May 19 '26 10:05

florisvb



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!