在python中使用while循环作为等待
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16720868/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using a while loop as a wait in python
提问by Ziggy
I have done this in C/C++ before where I have a while loop that acts as a wait holding the program up until the condition is broken. In Python I am trying to do the same with while(GPIO.input(24) != 0):and its says that it is expecting an indent. Is there anyway to get the script to hang on this statement until the condition is broken?
我在 C/C++ 中完成了这个之前,我有一个 while 循环,它充当等待程序直到条件被破坏的等待。在 Python 中,我试图做同样的事情while(GPIO.input(24) != 0):,它说它期待缩进。无论如何让脚本挂在这个语句上直到条件被破坏?
回答by Andy
Add a pass, as such:
添加一个pass,如下所示:
while(GPIO.input(24) != 0):
pass
You might also consider a different approach:
您也可以考虑采用不同的方法:
while True:
if GPIO.input(24) == 0: break
Whichever you think is more readable.
无论你认为哪个更具可读性。
回答by Platinum Azure
In Python, you need to use the passstatement whenever you want an empty block.
在 Python 中,pass只要需要一个空块,就需要使用该语句。
while (GPIO.input(24) != 0):
pass
回答by danodonovan
In python you can't leave the colon :hanging so you must use a passto complete the empty block. Another way to use a whilein this way
在 python 中,您不能让冒号:悬空,因此您必须使用 apass来完成空块。while以这种方式使用 a 的另一种方式
while True:
if GPIO.input(24) == 0:
break
回答by Asad Saeeduddin
Do note that an empty while loop will tend to hog resources, so if you don't mind decreasing the time resolution, you can include a sleepstatement:
请注意,空的 while 循环往往会占用资源,因此如果您不介意降低时间分辨率,则可以包含以下sleep语句:
while (GPIO.input(24) != 0):
time.sleep(0.1)
That uses less CPU cycles, while still checking the condition with reasonable frequency.
这使用更少的 CPU 周期,同时仍然以合理的频率检查条件。

