Python 运行while循环,直到函数返回值
我试图在函数运行时点亮一个5毫米的LED。当这个函数(下面详细介绍)完成并返回一个值时,我想中断while循环 while循环的当前代码:Python 运行while循环,直到函数返回值,python,Python,我试图在函数运行时点亮一个5毫米的LED。当这个函数(下面详细介绍)完成并返回一个值时,我想中断while循环 while循环的当前代码: pins = [3,5,8,15,16] def piBoard(): finished = 0 while finished!=10: for pin in pins GPIO.output( pin, GPIO.HIGH ) time.sleep(0.1) GPIO.ou
pins = [3,5,8,15,16]
def piBoard():
finished = 0
while finished!=10:
for pin in pins
GPIO.output(
pin, GPIO.HIGH
)
time.sleep(0.1)
GPIO.output(
pin, GPIO.LOW
)
finished+=1
现在在上面的例子中,我只是运行while循环,直到计数等于10,这不是最佳实践。如果我的下一个函数返回了一个值,我希望while循环中断
函数在返回while循环的值时,我希望中断while循环
def myFunction():
Thread(target = piBoard().start()
// Trying to recognize the song
return the song which is recognized
谢谢,-K.在while条件put true和while循环put if语句中,如果返回write break,则检查函数是否返回任何值。 您可以通过使用线程来实现这一点。 下面是示例代码
from concurrent.futures._base import as_completed
from concurrent.futures.thread import ThreadPoolExecutor
WORK_FINISHED = False
def piBoard():
while not WORK_FINISHED:
# Do some stuff
# Drink some coffee
def myFunction():
time.sleep(5)
global WORK_FINISHED
WORK_FINISHED = True #update gobal status flag
return something
if __name__ == '__main__':
futures = []
MAX_WORKERS = 5 #max number of threads you want to create
with ThreadPoolExecutor(MAX_WORKERS) as executor:
executor.submit(piBoard)
# submit your function to worker thread
futures.append(executor.submit(myFunction))
# if you need to get return value from `myFunction`
for fut in as_completed(futures):
res = fut.result()
希望这能有所帮助。我觉得您想编写一个类,扩展
线程
并实现\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
方法,使其在with
语句中工作。实现简单,语法简单,效果很好。该类将如下所示:
import threading
class Blinky(threading.Thread):
def __init__(self):
super().__init__()
self.daemon = True
self._finished = False
def __enter__(self):
self.start()
def __exit__(self, exc_type, exc_val, exc_tb):
self.stop()
def run(self):
# turn light on
while not self._finished:
time.sleep(.5)
# turn light off
def stop(self):
self._finished = True
然后,要运行您的函数,您只需输入:
with Blinky():
my_function()
当到达
with
语句时,指示灯应打开,并在with
的上下文退出后半秒内关闭。您需要某种线程间通信<代码>线程。事件非常简单
import threading
song_recognized_event = threading.event()
在歌曲识别器中,识别歌曲后调用set()
在LED循环中,在切换LED时偶尔检查isSet()
while not song_recognized_event.isSet():
# toggle LEDs
运行
clear()
重置它。使用decorator和asyncio,灵感来自@Eric Ed Lohmar:
import asyncio
def Blink():
from functools import wraps
async def _blink():
while True:
print("OFF")
await asyncio.sleep(.5)
print("ON")
await asyncio.sleep(.5)
def Blink_decorator(func):
@wraps(func)
async def wrapper(*args,**kwargs):
asyncio.ensure_future(_blink())
await func(*args,**kwargs)
return wrapper
return Blink_decorator
@Blink()
async def longTask():
print("Mission Start")
await asyncio.sleep(3)
print("Mission End")
def main():
loop = asyncio.get_event_loop()
loop.run_until_complete(longTask())
如果您只是在列表的每个元素上调用
myFunction
,那么只需使用for
就足够了。只需使用break
?也许这不是解决问题的正确方法。您能否更详细地描述一下您想要实现的功能,以便我们可以尝试更好的方法/解决方案(如果有的话)。好的,也许我没有完全解释我的用例。我基本上有两个功能。第一个(piBoard)可以点亮我的实验板上的一些LED,另一个功能可以使用库来识别音乐(比如Soundhound或Shazam)。我想让LED一直亮到第二个功能完成识别歌曲为止。因此,在我目前的情况下,我在10点之前做finished+=1
,这并不是我想要的。因为识别部分可能需要更长甚至更短的时间。因此,如果myFunction
返回了一些值,我想在while
和for
循环中中断。@matthia是对的!我也有。让我更新我的问题。