如何将参数传递给 Python 中的线程函数

How to pass arguments to thread functions in 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

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

[ ... ]

args is the argument tuple for the target invocation. Defaults to ().

所以我们可以根据需要提供 args:

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

But here I am not sure how do I pass the values High and Low to generate sound function.

这不依赖于对线程的理解;这是这些类型的“回调”函数的通用技术(基本上是任何时候将函数作​​为参数传递给其他东西)。例如,在使用 tkinter(或其他工具包)制作 GUI 时,您经常需要这种按钮技术。

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

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