简体   繁体   English

Python 多处理队列未向父进程发送数据

[英]Python multiprocessing queue not sending data to parent process

So I've got a bluetooth connection from an arduino reading a joystick and sending the axis readout over bluetooth to my raspberry pi (4b running ubuntu 20.10).所以我从 arduino 获得了蓝牙连接,读取操纵杆并将轴读数通过蓝牙发送到我的树莓派(4b 运行 ubuntu 20.10)。 I've confirmed it's receiving this data too.我已经确认它也收到了这些数据。

Now I try to run this bluetooth communcication in a separate process using the python multiprocessing module.现在我尝试使用 python 多处理模块在单独的进程中运行此蓝牙通信。 to access the data from the arduino, I give the function a queue from the parent main process to put the data in there.为了从 arduino 访问数据,我给 function 一个来自父主进程的队列,以便将数据放入其中。 Then in the main function I continuously try to read from this queue and process the data there.然后在主 function 中,我不断尝试从该队列中读取并处理那里的数据。

The queue in the parent process always remains empty, however, and as such I can't process the data any further.但是,父进程中的队列始终为空,因此我无法进一步处理数据。

How can I get the data from the bluetooth process back to the main process?如何将蓝牙进程中的数据返回到主进程?

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

At thelizardking34's suggestion, I relooked at the global stuff I'd been messing with and after correcting it, the code as now given in the question works.在 thelizardking34 的建议下,我重新查看了我一直在搞乱的全局内容,在更正之后,问题中给出的代码有效。

Thanks to thelizardking34!感谢蜥蜴王34!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM