问题描述
在两个独立的Python运行时之间进行通信的好方法是什么?我尝试过的东西:
What is a good way to communicate between two separate Python runtimes? Thing's I've tried:
我的基本要求是能够运行python listen.py
并使该进程就可以在其中执行操作,例如守护程序,能够从python client.py --bar
接收消息.客户端调用应仅向现有流程发送一条消息并终止,并以成功返回代码0
或失败返回非零值(即需要某种双向通信)
My basic requirement is to be able to run python listen.py
and have that process just doing it's thing there, like a daemon, able to receive messages from python client.py --bar
. The client call should just send a message to the existing process and terminate, with return code 0
for success or nonzero for failure (i.e. some two-way communication will be required)
推荐答案
multiprocessing
库提供了侦听器和客户端,用于包装套接字并允许您传递任意的python对象.
The multiprocessing
library provides listeners and clients that wrap sockets and allow you to pass arbitrary python objects.
您的服务器可以侦听接收到的python对象:
Your server could listen to receive python objects:
from multiprocessing.connection import Listener
address = ('localhost', 6000) # family is deduced to be 'AF_INET'
listener = Listener(address, authkey='secret password')
conn = listener.accept()
print 'connection accepted from', listener.last_accepted
while True:
msg = conn.recv()
# do something with msg
if msg == 'close':
conn.close()
break
listener.close()
您的客户端可以将命令作为对象发送:
Your client could send commands as objects:
from multiprocessing.connection import Client
address = ('localhost', 6000)
conn = Client(address, authkey='secret password')
conn.send('close')
# can also send arbitrary objects:
# conn.send(['a', 2.5, None, int, sum])
conn.close()
这篇关于Python中的进程间通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!