Python同时做这两件事,多任务处理还是不处理


编辑

来自manish和njzk2的建议:

现在我记得我试着使用when_motion,但得到了:

类型错误:"NoneType"对象不可调用

当放在动作中时。

像您建议的那样把它放在函数之外似乎是个好主意,但错误仍然会弹出并中断。inventory()尽管没有发生任何动作,但声音也立即播放

我所做的:

from PN5180 import PN5180
from gpiozero import MotionSensor
import vlc
player = vlc.MediaPlayer()
def play(element):
print ("{}!".format(element))
player.set_media(vlc.Media("{}.wav".format(element)))
player.play()
while True:


cards = PN5180().inventory()
print(f"{len(cards)} card(s) detected: {' - '.join(cards)}")
cardcount = len(cards)

MotionSensor(17).when_motion(Play("feu"))

仍有错误:

运动传感器(17)when_motion(播放("feu"))

类型错误:"NoneType"对象不可调用

即使在最简单的情况下:

from gpiozero import MotionSensor
While true:
MotionSensor(17).when_motion()
print("motion detected")

返回错误。

这意味着什么?


我目前正在尝试设置我的第一个python/树莓pi项目

为了与rfid读取器接口,我正在使用此库:https://github.com/fservida/pyPN5180

它包含了一种可用的方法,即返回多达16个nfc呈现芯片的列表。据我所知,为了让它更新,你需要把它放在一个循环中。

from PN5180 import PN5180
reader = PN5180
while True:
cards = reader.inventory() #getting the list
print(f"{len(cards)} card(s) detected: {' - '.join(cards)}")
time.sleep(.4)

我想经常听芯片,同时也听3个运动传感器的运动

但如果我添加传感器功能

from PN5180 import PN5180
reader = PN5180
while True:
cards = reader.inventory() #getting the list
print(f"{len(cards)} card(s) detected: {' - '.join(cards)}")
time.sleep(.4)
mySensorFonction()

然后卡片列表不再迭代/更新,把卡片放在读卡器上也不会触发任何我称之为的东西

这是传感器的功能以防万一:

from gpiozero import MotionSensor
import vlc
player = vlc.MediaPlayer()
def PirSound(pin, element):

pir = MotionSensor(pin=pin)
pir.wait_for_motion()
print ("{}!".format(element))
player.set_media(vlc.Media("{}.wav".format(element)))
player.play()


我希望检测到的芯片列表在做其他事情的同时不断更新,并且能够在我想触发事件和状态的任何时候提取列表中的内容

在快速搜索时,我偶然发现了多任务库。这是我的解决方案吗?你会怎么安排?

希望它足够清楚^^

使用

def play():
print ("{}!".format(element))
player.set_media(vlc.Media("{}.wav".format(element)))
player.play()
and 
pir.when_motion(play)

而不是调用CCD_ 1。

wait_for_motion正在阻塞(…它等待运动),而when_motion注册一个回调,当检测到运动时调用该回调。

据我所知,您正在寻找的是多线程,python中的多线程实现称为线程,下面是Geeks for Geeks链接的一个很好的解释+教程

最新更新