python while循环等待条件更改或timeou

2024-04-24 20:55:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在python中构造一个while循环,等待某个条件(函数foo)改变,或者在指定的时间后给出超时。下面是我如何编码的

def wait_change():
  import time
  timeout = 10 # time out of 10 seconds for example

  # set initial time and initial variables
  start_time = time.time()
  current_time = 0
  start_state = foo()
  current_state = start_state

  while current_time<timeout and start_state==current_state:
    current_time = time.time()-start_time
    current_state = foo()

 if current_time<timeout:
   return None
 else:
   return current_state

这个函数运行得很好,但我不确定这是否是实现它的最佳方法。重要的是我要检查某个状态并返回它,并在超时时通知调用函数(这里返回None)。 这是最好的实现,还是有一种更python的方法来处理它?尤其是我很担心

  • 对函数foo进行两次调用
  • 如果返回值合适(即wither返回值或None
  • 如果使用signalthreading可能会更有用,从而得到更好的代码

谢谢, 亚历克斯


Tags: and方法函数nonereturnfootimetimeout