[英]How to pass arguments to thread functions in Python
我有raspberry pi
派,我正在使用 python 创建一个小的蜂鸣器脚本。 在脚本中,如果条件变为True
,我需要打印一些信息并发出蜂鸣声。 蜂鸣器声音有两种不同的格式,即High
和Low
。 在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 秒,然后打印信息。
为了解决这个问题,我将生成声音 function 放在一个线程中,以便它可以与打印信息并行运行,如下所示:
sound = Thread(target=generate_sound)
但是在这里我不确定如何传递值High
和Low
来生成声音 function。 我不是线程方面的专家。 谁能给我一些想法。 请帮忙。 谢谢
赦免; 有反身习惯。 特别是线程库为您提供了直接的解决方案,因此无需使用该行下方的解决方法。
请参阅线程文档:
class
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 来生成声音 function。
这不依赖于理解线程; 这是此类“回调”函数的通用技术(基本上,只要您将 function 作为参数传递给其他东西)。 例如,在使用 tkinter(或其他工具包)制作 GUI 时,您经常需要这种按钮技术。
将参数绑定到调用,例如使用标准库中的functools.partial
:
from functools import partial
sound = Thread(target=partial(generate_sound, 'High'))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.