2017-07-25 55 views
0

我試圖在運行某個函數時點亮5mm LED。當這個函數(關於下面的更多細節)完成並返回一個值時,我想打破while循環。運行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.output(
     pin, GPIO.LOW 
    ) 
    finished+=1 

現在在上面的例子中,我只需運行while循環,直到計數等於10,而不是最好的做法。如果我的下一個函數返回值,我希望while循環中斷。

功能我想打破我的while循環,當返回其值

def myFunction(): 
    Thread(target = piBoard().start() 
    // Trying to recognize the song 
    return the song which is recognized 

謝謝, - K.

+1

如果你只是調用列表中的每個元素'myFunction',只是'for'應該足夠了。 – Carcigenicate

+0

只是使用'break'? – frozen

+0

也許這不是一個正確的方法來解決你的問題。你可以更詳細地描述你想要達到的目標,以便我們可以嘗試更好的方法/解決方案。 – anekix

回答

1

這聽起來像你想寫一個類延伸Thread和實施__enter____exit__方法,使其在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的背景下退出。

0

在while條件while循環把if語句把真實,這將檢查你的函數返回任何值如果返回寫入中斷

0

如果你打算使用線程。 你可以通過使用線程來實現這一點。 這裏的示例代碼

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() 

希望這會有所幫助。

0

您需要某種線程間通信。 threading.Event就像你可以得到的一樣簡單。

import threading 

song_recognized_event = threading.event() 

在您的歌曲識別器中,一旦歌曲被識別,請致電set()

在您的LED迴路中,偶爾檢查isSet(),同時切換LED。

while not song_recognized_event.isSet(): 
    # toggle LEDs 

運行clear()重置它。

0

使用裝飾和ASYNCIO,通過@Eric埃德洛馬爾啓發:

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())