在给定的超时时间内等待条件

问题描述 投票:0回答:2

我想知道是否有足够的方法或模块在给定的超时时间内等待条件(返回 bool 的函数)?示例

def wait_for_condition(condition,  timeout, interval) :
    # implementation 
    # return True if the condition met in given timeout, else return False

提前致谢!

python wait
2个回答
11
投票

我会简单地推出你自己的,这看起来很简单:

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)

0
投票

我喜欢@alpha1554之前的回答,但想返回是否有超时。另外,由于可以使用 lambda 来调用它,所以我觉得不需要采用 *args 并将它们传递给谓词。这是我的变体:

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

使用带有参数且具有非布尔返回值的谓词来调用它:

wait_for(lambda: get_some_status(some_arg) != "IN_PROGRESS")
© www.soinside.com 2019 - 2024. All rights reserved.