如何在Python中将参数传递给线程函数 [英] How to pass arguments to thread functions in Python

查看:14
本文介绍了如何在Python中将参数传递给线程函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在raspberry pi中使用了python来创建一个小的蜂鸣器脚本。在脚本中,如果条件变为True,我需要打印一些信息并发出蜂鸣器的声音。蜂鸣器的声音有两种不同的格式,即HighLow。在High中,我必须运行以下代码:

GPIO.output(BUZZER, 1)
time.sleep(5)
GPIO.output(BUZZER, 0)
GPIO.cleanup()
使蜂鸣器连续发出5秒声音。在Low中,我必须运行以下代码:

for i in range(5):
    print(i)
    state = GPIO.input(BUZZER)
    print("state is {}".format(state))
    GPIO.output(BUZZER, 1)
    time.sleep(0.3)

    state = GPIO.input(BUZZER)
    print("state is {}".format(state))
    GPIO.output(BUZZER, 0)
    time.sleep(0.3)

它将发出5声嘟嘟声。

以下是python脚本:

def generate_sound(tempo):
    if tempo == "High":
        GPIO.output(BUZZER, 1)
        time.sleep(5)
        GPIO.output(BUZZER, 0)
        GPIO.cleanup()
    else:
        for i in range(5):
            state = GPIO.input(BUZZER)
            print("state is {}".format(state))
            GPIO.output(BUZZER, 1)
            time.sleep(0.3)

            state = GPIO.input(BUZZER)
            print("state is {}".format(state))
            GPIO.output(BUZZER, 0)
            time.sleep(0.3)



if some_condition is True:
    generate_sound("High")
    print("This condition is True")
    print("Here is the information you need")
    print("Some more information")

else:
    generate_sound("Low")
    print("This condition is False")
    print("Here is the information you need")
    print("Some more information")
上面的代码运行良好,但问题是我必须同时显示信息和发出声音。但在目前的方法中,声音会产生并等待5秒,然后打印信息。

为了解决这个问题,我想将生成声音的函数放在一个线程中,这样它就可以与打印信息并行运行,如下所示:

sound = Thread(target=generate_sound)

但这里我不确定如何传递HighLow值来生成声音函数。我对穿线不是很在行。有没有人能给我一些建议。请帮帮忙。谢谢

推荐答案

对不起;那里有条件反射的习惯。线程库特别为您提供了直接的解决方案,因此不需要线下的变通方法。

参见Thread documentation

threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

[...]

args是目标调用的参数元组。默认为()

因此我们只能根据需要提供args

# Note the comma in `('High',)`; we want a 1-element tuple.
sound = Thread(target=generate_sound, args=('High',))

但在这里我不确定如何传递High和Low值以生成声音函数。

这并不依赖于对线程的理解;它是此类&回调&函数(基本上是将函数作为参数传递给其他函数的任何时候)的通用技术。例如,在使用tkinter(或其他工具包)制作图形用户界面时,您经常需要对按钮使用此技术。

将参数绑定到调用,例如使用标准库中的functools.partial

from functools import partial
sound = Thread(target=partial(generate_sound, 'High'))

这篇关于如何在Python中将参数传递给线程函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆