【发布时间】:2020-02-13 13:25:34
【问题描述】:
我正在使用 Google Protocol Buffers 和 Python 来解码一些大型数据文件——每个文件 200MB。我下面有一些代码显示了如何解码分隔流,它工作得很好。但是,它使用read() 命令将整个文件加载到内存中,然后对其进行迭代。
import feed_pb2 as sfeed
import sys
from google.protobuf.internal.encoder import _VarintBytes
from google.protobuf.internal.decoder import _DecodeVarint32
with open('/home/working/data/feed.pb', 'rb') as f:
buf = f.read() ## PROBLEM-LOADS ENTIRE FILE TO MEMORY.
n = 0
while n < len(buf):
msg_len, new_pos = _DecodeVarint32(buf, n)
n = new_pos
msg_buf = buf[n:n+msg_len]
n += msg_len
read_row = sfeed.standard_feed()
read_row.ParseFromString(msg_buf)
# do something with read_metric
print(read_row)
请注意,此代码来自另一个 SO 帖子,但我不记得确切的网址。我想知道是否有与协议缓冲区等效的readlines() 允许我一次读取一个分隔消息并对其进行解码?我基本上想要一个不受 RAM 限制的管道,我必须加载文件。
似乎有一个pystream-protobuf 包支持其中的一些功能,但它在一两年内没有更新。 7年前也有一篇帖子问过类似的问题。但我想知道从那以后是否有任何新信息。
python example for reading multiple protobuf messages from a stream
【问题讨论】:
-
我认为 SO 问题可能是这个问题:stackoverflow.com/questions/11484700/…