florisvb
florisvb

Reputation: 81

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

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.

Upvotes: 3

Views: 2411

Answers (1)

florisvb
florisvb

Reputation: 81

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)

Upvotes: 3

Related Questions