Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an easy way in Python to wait until certain condition is true?

Tags:

python

I need to wait in a script until a certain number of conditions become true?

I know I can roll my own eventing using condition variables and friends, but I don't want to go through all the trouble of implementing it, since some object property changes come from external thread in a wrapped C++ library (Boost.Python), so I can't just hijack __setattr__ in a class and put a condition variable there, which leaves me with either trying to create and signal a Python condition variable from C++, or wrap a native one and wait on it in Python, both of which sound fiddly, needlessly complicated and boring.

Is there an easier way to do it, barring continuous polling of the condition?

Ideally it would be along the lines of

res = wait_until(lambda: some_predicate, timeout) if (not res):     print 'timed out' 
like image 242
Alex B Avatar asked May 07 '10 02:05

Alex B


People also ask

How do you wait until something in Python?

You might need to wait for another function to complete, for a file to upload, or simply to make the user experience smoother. If you've got a Python program and you want to make it wait, you can use a simple function like this one: time. sleep(x) where x is the number of seconds that you want your program to wait.

How do you wait a minute in Python?

“python sleep for 1 minute” Code Answer'ssleep(60) # Delay for 1 minute (60 seconds).


1 Answers

Unfortunately the only possibility to meet your constraints is to periodically poll, e.g....:

import time  def wait_until(somepredicate, timeout, period=0.25, *args, **kwargs):   mustend = time.time() + timeout   while time.time() < mustend:     if somepredicate(*args, **kwargs): return True     time.sleep(period)   return False 

or the like. This can be optimized in several ways if somepredicate can be decomposed (e.g. if it's known to be an and of several clauses, especially if some of the clauses are in turn subject to optimization by being detectable via threading.Events or whatever, etc, etc), but in the general terms you ask for, this inefficient approach is the only way out.

like image 128
Alex Martelli Avatar answered Sep 23 '22 19:09

Alex Martelli