【问题标题】:Python multiprocessing queue not sending data to parent processPython多处理队列不向父进程发送数据
【发布时间】:2021-04-30 15:44:07
【问题描述】:

所以我有一个来自 arduino 的蓝牙连接,它读取操纵杆并将轴读数通过蓝牙发送到我的树莓派(4b 运行 ubuntu 20.10)。我已经确认它也收到了这些数据。

现在我尝试使用 python 多处理模块在单独的进程中运行此蓝牙通信。为了从 arduino 访问数据,我给该函数一个来自父主进程的队列,以将数据放入其中。然后在主函数中,我不断尝试从这个队列中读取数据并在那里处理数据。

但是,父进程中的队列始终为空,因此我无法进一步处理数据。

如何将蓝牙进程中的数据传回主进程?

main.py
#!/usr/bin/env python3
import time
import logging
import multiprocessing as mp
import bluetoothlib

logging.basicConfig(level=logging.DEBUG)

logging.info("creating queue")
global q
q = mp.Queue()      

def main():
    try:
        logging.info("starting bluetooth process")
        p = mp.Process(target=bluetoothlib.serlistener, args=(q,))
        p.start()
    except:
        logging.error("unable to start bluetooth listener")
        
    logging.info("start reading from queue")
    while True:
        #logging.info(q.qsize())
        if not q.empty():
            mss = q.get()
            logging.info(mss)
            #do something with data
        elif q.empty():
            logging.info("queue empty")
            
        time.sleep(1)
            

main()
bluetoothlib.py
#!/usr/bin/env python3
import os
import serial
import io

def serlistener(q):
    print ("creating connection")
    btConn = serial.Serial("/dev/rfcomm0", 57600, timeout=1)
    btConn.flushInput()
    sio = io.TextIOWrapper(io.BufferedRWPair(btConn, btConn, 1),encoding="utf-8")
    
    print ("connection created, starting listening")
    while btConn.is_open:
        try:
            mss = sio.readline()
            q.put(mss)
        except:
            print("error")                                                                              
            break

【问题讨论】:

  • 你为什么使用'全局队列';然后将对象 q 传递给 serlistener 函数;然后调用“队列”获取和放置?似乎您正在主线程中调用全局队列;但 q 对象中的预期消息。
  • @thelizardking34 哦,哎呀忘了在这里修复,我确实在实际程序中修复了它但没有任何成功,我现在将在问题中修复它
  • 程序记录“队列为空”是否正确?
  • @thelizardking34 是的,至少它确实做到了。现在修复了全局问题,它可以工作了!感谢您的帮助!

标签: python python-3.x multiprocessing queue raspberry-pi4


【解决方案1】:

在 thelizardking34 的建议下,我重新查看了我一直在搞乱的全局内容,在更正之后,问题中现在给出的代码有效。

感谢蜥蜴王34!

【讨论】:

  • 可能值得将您的全局声明重新添加到帖子中,并对导致问题的原因发表评论,以供后代使用:D
猜你喜欢
  • 2010-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-23
  • 2017-08-29
  • 2021-05-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多