Reputation: 2887
I was wondering if there was a sufficient way or a module to wait for a condition(function that returns bool), in given timeout? Example
def wait_for_condition(condition, timeout, interval) :
# implementation
# return True if the condition met in given timeout, else return False
Thanks in advance!
Upvotes: 9
Views: 13586
Reputation: 11
I love the prior answer by @alpha1554, but wanted to return whether there was a timeout or not. Also, since one could call it with a lambda I didn't feel the need to take *args and pass them to the predicate. Here is my variation:
def wait_for(pred, poll_sec=5, timeout_sec=600):
start = time.time()
while not (ok := pred()) and (time.time() - start < timeout_sec):
time.sleep(poll_sec)
return ok
Calling it with a predicate that takes args and has non-bool return value:
wait_for(lambda: get_some_status(some_arg) != "IN_PROGRESS")
Upvotes: 1
Reputation: 605
I would simply roll your own, this seems simple enough :
def wait_until(condition, interval=0.1, timeout=1, *args):
start = time.time()
while not condition(*args) and time.time() - start < timeout:
time.sleep(interval)
Upvotes: 11