[英]How to use time.sleep in an if statement and not stop the rest of the script
我有一个使用一会儿true并继续运行的python脚本。 在while循环中,我有几个if语句。 一些if语句中有一个time.sleep
。 使用了一段时间后,我注意到在time.sleep
下面的所有if语句都在等待。
有没有办法让if语句在time.sleep
以下运行或它们总是等待?
我可以将所有带有time.sleep
的if语句放在底部,这样所有没有time.sleep
的if语句都将首先执行。 除非有另一种方法,否则我将尝试以这种方式在运行脚本上构建该方法。
while True:
temp1 = tempRead1()
if temp1 < 65:
GPIO.output(17, False)
else:
GPIO.output(17, True)
if temp1 > 70 and GPIO.input(17):
time.sleep(120)
GPIO.output(27, False)
else:
GPIO.output(27, True)
if temp1 > 72 and GPIO.input(17):
time.sleep(120)
GPIO.output(22, False)
else:
GPIO.output(22, True)
if temp1 > 80 and GPIO.input(17):
time.sleep(120)
GPIO.output(5, False)
else:
GPIO.output(5, True)
if temp1 < 55:
GPIO.output(6, False)
else:
GPIO.output(6, True)
time.sleep(60)
从您的描述中听起来,您希望每个if / else同时并行执行? 照原样,即使您对语句重新排序,调用sleep也会使当前线程休眠,并且由于您的程序是单线程的,因此执行将在指定的时间停止执行,然后继续执行(这意味着执行的if会在评估下一个if / else语句之前进入睡眠状态)。
但是,您不必担心真正的同时执行,而是为什么不将if / elses重新组织为仅包含一条sleep语句。 这是一些入门的shell代码。
if not GPIO.input(17) :
# not going to sleep, add relevant if checks here
...
else:
# do all the if checks
sleep = temp1 > 72 or temp1 ..... etc
sleeping = [temp1 > 72, temp1 > ...]
if sleep:
time.sleep(120)
#ok, now drive GPIO outs
if sleeping[0]:
GPIO.output(22, False)
else:
GPIO.output(22, True)
...
简单的答案是,出于您在此脚本中的目的,您不能不使用某种形式的线程代码,在if...statements
只需为睡眠期定义一个变量,然后在循环的底部进行定义,
if sleep_time != 0:
time.sleep(sleep_time)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.