Python线程化子函数

2024-04-19 11:48:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我的应用程序正在循环中运行。。有时它需要从循环中调用一个led flash函数。我差不多是这样做的

def led_red_flash(flashcount):
        logging.debug('Starting')

        for l in range(0,flashcount):
                GPIO.output(16,GPIO.HIGH)
                time.sleep(0.1)
                GPIO.output(16,GPIO.LOW)
                time.sleep(0.1)
        logging.debug('Stopping')

while True:
       <do some stuff here>
       t = threading.Thread(name='led_red_flash', target=led_red_flash(100) )
       t.start()

这很管用。。但是有没有一天可以把所有的线程都放到def-led-red-flash部分呢?随着我的脚本变得越来越复杂,它将使它更难阅读。像这样的事情

while True:
       <do some stuff here>
       led_red_flash(100)

上面是我正在运行的循环的一个非常简化的版本。在实际脚本中,不可能同时运行多个led\ red\ flash实例。。所以这不是问题。你知道吗


Tags: debugtrueoutputledgpiotimeloggingdef
1条回答
网友
1楼 · 发布于 2024-04-19 11:48:57

可以创建包装函数:

def _led_red_flash(flashcount):
    logging.debug('Starting')
    for l in range(0,flashcount):
        GPIO.output(16,GPIO.HIGH)
        time.sleep(0.1)
        GPIO.output(16,GPIO.LOW)
        time.sleep(0.1)
    logging.debug('Stopping')


def led_red_flash(flashcount):
    t = threading.Thread(name='led_red_flash', target=_led_red_flash, args=(100,))
    t.start()
    return t

顺便说一句,您的原始代码没有在单独的线程中执行led_red_flash。我刚刚调用了led_red_flashled_red_flash(100))。你知道吗

应该传递函数本身,而不是函数调用的返回值。见^{}。你知道吗

threading.Thread(name='led_red_flash', target=led_red_flash(100))

threading.Thread(name='led_red_flash', target=led_red_flash, args=(100,))

相关问题 更多 >