Python中的进程间通信 [英] Interprocess communication in Python

查看:88
本文介绍了Python中的进程间通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在两个独立的Python运行时之间进行通信的好方法是什么?我尝试过的东西:

What is a good way to communicate between two separate Python runtimes? Thing's I've tried:

  • 在命名管道上读取/写入,例如 os.mkfifo (感觉很hacky)
  • dbus 服务(在台式机上工作,但重量太大,无法装上头)
  • 套接字(似乎太低级了,肯定有一个更高级别的模块可以使用吗?)

我的基本要求是能够运行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中的进程间通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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