运行while循环,直到函数返回值

时间:2017-07-25 17:22:07

标签: python

我正在尝试在功能运行时点亮5mm 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.output(
        pin, GPIO.LOW
      )
    finished+=1

现在在上面的例子中我只运行while循环,直到count等于10,而不是最佳实践。如果我的下一个函数返回了值,我希望while循环中断。

功能我希望在返回其值时打破我的while循环

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

谢谢, - K。

5 个答案:

答案 0 :(得分: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的上下文后关闭半秒钟。

答案 1 :(得分:0)

在while条件设置为true并且在while循环中放置if语句将检查函数是否返回任何值,如果返回写入中断

答案 2 :(得分:0)

如果您愿意使用线程。 你可以通过使用线程来实现这一点。 这是示例代码

`$ 60  :List of 1
..$ results:'data.frame':   1 obs. of  5 variables:
.. ..$ address_components:List of 1
.. .. ..$ :'data.frame':    8 obs. of  3 variables:
.. .. .. ..$ long_name : chr [1:8] "119" "Avenida Diego Díaz de Berlanga" 
"Jardines de Anahuac 2do Sector" "San Nicolás de los Garza" ...
.. .. .. ..$ short_name: chr [1:8] "119" "Avenida Diego Díaz de Berlanga" 
"Jardines de Anahuac 2do Sector" "San Nicolás de los Garza" ...
.. .. .. ..$ types     :List of 8
.. .. .. .. ..$ : chr "street_number"
.. .. .. .. ..$ : chr "route"
.. .. .. .. ..$ : chr [1:3] "political" "sublocality" "sublocality_level_1"
.. .. .. .. ..$ : chr [1:2] "locality" "political"
.. .. .. .. ..$ : chr [1:2] "administrative_area_level_2" "political"
.. .. .. .. ..$ : chr [1:2] "administrative_area_level_1" "political"
.. .. .. .. ..$ : chr [1:2] "country" "political"
.. .. .. .. ..$ : chr "postal_code"
.. ..$ formatted_address : chr "Avenida Diego Díaz de Berlanga 119, Jardines 
de Anahuac 2do Sector, 66444 San Nicolás de los Garza, N.L., Mexico"
.. ..$ geometry          :'data.frame': 1 obs. of  3 variables:
.. .. ..$ location     :'data.frame':   1 obs. of  2 variables:
.. .. .. ..$ lat: num 25.7
.. .. .. ..$ lng: num -100
.. .. ..$ location_type: chr "ROOFTOP"
.. .. ..$ viewport     :'data.frame':   1 obs. of  2 variables:
.. .. .. ..$ northeast:'data.frame':    1 obs. of  2 variables:
.. .. .. .. ..$ lat: num 25.7
.. .. .. .. ..$ lng: num -100
.. .. .. ..$ southwest:'data.frame':    1 obs. of  2 variables:
.. .. .. .. ..$ lat: num 25.7
.. .. .. .. ..$ lng: num -100
.. ..$ place_id          : chr "ChIJRY_wPdqUYoYRTJetT6AJETA"
.. ..$ types             :List of 1
.. .. ..$ : chr "street_address"

希望这有帮助。

答案 3 :(得分:0)

您需要某种线程间通信。 threading.Event就像你能得到的一样简单。

import threading

song_recognized_event = threading.event()

在您的歌曲识别器中,一旦识别出歌曲,请拨打set()

在LED循环中,在切换LED时偶尔检查isSet()

while not song_recognized_event.isSet():
    # toggle LEDs

运行clear()重置它。

答案 4 :(得分:0)

使用装饰者和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())
相关问题