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

后端 未结 8 1358

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 wa

8条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-23 21:07

    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.

提交回复
热议问题