goo*_*ofd 1 python zeromq pyzmq
我想从多个进程写入一个文件.确切地说,我宁愿不使用多处理队列解决方案进行多处理,因为有几个子模块由其他开发人员编写.但是,对此类子模块的每次写入都与写入zmq队列相关联.有没有办法将zmq消息重定向到文件?具体来说,我正在寻找http://www.huyng.com/posts/python-logging-from-multiple-processes/的内容,而不使用该logging模块.
这很简单.在一个过程中,绑定PULL套接字并打开文件.每次PULL套接字收到消息时,它都会直接写入该文件.
EOF = chr(4)
import zmq
def file_sink(filename, url):
"""forward messages on zmq to a file"""
socket = zmq.Context.instance().socket(zmq.PULL)
socket.bind(url)
written = 0
with open(filename, 'wb') as f:
while True:
chunk = socket.recv()
if chunk == EOF:
break
f.write(chunk)
written += len(chunk)
socket.close()
return written
Run Code Online (Sandbox Code Playgroud)
在远程进程中,创建一个Proxy对象,其write方法只是通过zmq发送消息:
class FileProxy(object):
"""Proxy to a remote file over zmq"""
def __init__(self, url):
self.socket = zmq.Context.instance().socket(zmq.PUSH)
self.socket.connect(url)
def write(self, chunk):
"""write a chunk of bytes to the remote file"""
self.socket.send(chunk)
Run Code Online (Sandbox Code Playgroud)
而且,只是为了好玩,如果你打电话Proxy.write(EOF),接收过程将关闭文件并退出.
如果要编写多个文件,可以通过启动多个接收器并为每个文件设置一个URL,或者使接收器稍微复杂一些,并使用多部分消息来指示要写入的文件,从而相当容易地执行此操作.