3

Python中简便的多进程通信方法

 2 years ago
source link: https://allenwind.github.io/blog/13249/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Mr.Feng Blog

NLP、深度学习、机器学习、Python、Go

Python中简便的多进程通信方法

命令行交互下,多个Python解释器中通信的简便方法。

在Python交互命令行下,有时候我们需要在两个进程(解释器)间通信数据,比如在一个解释器下完成复杂的数据预处理,想把它传到另外一个新环境(解释器)下做更多的尝试(这些操作可能不安全甚至可能会让解释器挂掉)而不影响原理的环境。

无论是使用socket还是第三方数据库如sqlite、Redis、MySQL、MongoDB、Celery都很麻烦,毕竟引入相关库依赖而且这些都是试验性操作,没有必要存数据库。这里提供一种不带依赖的方法快速实现解释器间通信数据。

在Python3中,这个功能内置到标准库multiprocessing.connection中。在Linux下,其通信协议使用Unix域套接字,通信对象会通过pickle序列化再发送。两个解释器之间的通信支持简单的认证。

在解释器二,建立Listener(Server),用来接收解释器一的数据,

from multiprocessing.connection import Listener
address = ("localhost", 8080)
authkey = b"qwerty" # 用来进行hmac认证,注意是bytes类型
server = Listener(address, authkey=authkey)
conn = server.accept() # 接受连接
data = conn.recv() # 接收数据
print(data.shape)

在第一个解释器建立Client,把处理好的数据发送给解释器二,

import numpy as np
from multiprocessing.connection import Client
address = ("localhost", 8080)
authkey = b"qwerty"
client = Client(address, authkey=authkey)

data = np.random.uniform(size=(1000, 1000)) # 模拟处理好的数据
client.send(data) # 发送数据

这种方法是不是比使用socket还是第三方数据库如sqlite、Redis、MySQL、MongoDB、Celery很好多,不引入外部依赖,不需要第三方库。不过要注意,以上server和client只在建立握手后使用hmac认证,详细看旧文使用hmac进行socket认证,后续数据send和recv都是非加密的,需要确保网络环境是否安全。

经过测试,可以传递Tensorflow对象和Numpy对象。

转载请包括本文地址:https://allenwind.github.io/blog/13249
更多文章请参考:https://allenwind.github.io/blog/archives/


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK