python使用Connection实现多进程之间通信,pythonconnection,在python的mult


在python的multiprocessing.connection包中有Listener和Client类可以实现多进程之间的通信,这种通信方式根据平台的不同会自动选择socket或者named pipe的方式来实现通信。

下面是我开发中用的例子,multiprocess_server.py调用jieba为其他进程提供分词服务,其简略的实现代码如下:

#encoding=utf-8__author__ = 'byrx.net'from multiprocessing.connection import Listenerimport jiebaaddress = ('localhost', 6000)     # family is deduced to be 'AF_INET'listener = Listener(address, authkey='secret password')while True:    conn = listener.accept()    print 'connection accepted from', listener.last_accepted    data = conn.recv()    try:        result = ','.join(list(jieba.cut(data,False)))        result = result.encode('utf-8')        conn.send_bytes('get %s'%(result,))    except Exception,e:        print e    finally:        conn.close()listener.close()

客户端使用服务器端分词的代码如下:

#encoding=utf-8__author__ = 'byrx.net'from multiprocessing.connection import Clientaddress = ('localhost', 6000)for x in range(0,5000):    conn = Client(address, authkey='secret password')    conn.send('这是一个美丽的世界')    print conn.recv_bytes()    conn.close()

评论关闭