在两个Python进程之间交换数据 [英] Exchange data between two Python processes

查看:342
本文介绍了在两个Python进程之间交换数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Arduino,可将JSON数据包发送到Python进程(PP1).该Python进程将连续运行.但是,此过程必须邀请并接收JSON数据包到另一个Python过程(PP2).基本上,PP1必须将从Arduino接收到的JSON数据包传递给PP2.而且PP1必须从PP2接收命令包(也可以是JSON格式).

I have an Arduino which sends a JSON packet to a Python process (PP1). This Python process will run continuously. But this process has to invite and receive JSON packets to another Python process (PP2). Basically PP1 has to pass the JSON packet received from Arduino to PP2. And PP1 has to receive commands packets from PP2 (can be in JSON format too).

链接到建筑图片:

下面是开始Python流程1的代码

Bellow a begin the code of Python process 1

import json

#open port
serialport = serial.Serial('COM5',38400,timeout=1,stopbits=serial.STOPBITS_TWO);
time.sleep(1);

#loop
while(True):
    #receive arduino data
    receive = serialport.readline()

    #vparse json
    try:
        test = json.loads(receive)
    except:
        print Exception.message
    else:
        print json.dumps(test)

您知道执行此操作的简单方法吗?多线程是必需的吗?

Do you know a simple way to do this? Is multithreading necessary?

推荐答案

您将需要某处"来放置数据.最简单的解决方案是使用multiprocessing.Queue,如果需要扩展,也许您可​​以调查一些工作队列(休伊,芹菜,django_q).

You'll need "somewhere" to put your data. The most simple solution would be using multiprocessing.Queue, if you need to scale maybe you can look into some job queue (huey, celery, django_q).

使用multiprocessing.Queue的示例:

import multiprocessing

def pp1(q, data):
      processed_data = data_processing(data) # do some data processing and its result
      q.put(processed_data)

def pp2(q):
    result = q.get()
    show_results(result) # show results to the user


if __name__ == '__main__':
    queue = multiprocessing.Queue()

    process_1 = multiprocessing.Process(target=pp1, args=(queue,))
    process_1.start()

    process_2 = multiprocessing.Process(target=pp2, args=(queue,))
    process_2.start()

您的循环将是data_processingshow_results(虚拟)函数.

Your loops would be the data_processing and show_results (dummy) functions.

您可以在此处阅读有关过程通信的更多信息: https://pymotw.com/3/multiprocessing/communication.html

You can read more about process communication here: https://pymotw.com/3/multiprocessing/communication.html

希望有帮助

这篇关于在两个Python进程之间交换数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆