我正在处理来自 spinn3r 的数据,它由序列化为字节流的多个不同的 protobuf 消息组成:
http://code.google.com/p/spinn3r-client/wiki/Protostream http://code.google.com/p/spinn3r-client/wiki/Protostream
“protostream 是一个协议缓冲区消息流,根据 Google 协议缓冲区规范在线路上编码为长度前缀的变体。该流由三个部分组成:标头、有效负载和尾部标记。”
这似乎是 protobuf 的一个非常标准的用例。事实上,protobuf 核心发行版为 C++ 和 Java 提供了 CodedInputStream。但是,protobuf 似乎没有为 python 提供这样的工具——“内部”工具不是为这种外部使用而设置的:
https://groups.google.com/forum/?fromgroups#!topic/protobuf/xgmUqXVsK-o https://groups.google.com/forum/?fromgroups#!topic/protobuf/xgmUqXVsK-o
所以......在我去拼凑一个 python varint 解析器和用于解析不同消息类型流的工具之前:有人知道这方面的工具吗?
为什么 protobuf 中缺少它? (或者我只是没找到它?)
对于 protobuf 来说,这似乎是一个很大的差距,特别是与 thrift 的“传输”和“协议”等价工具相比。我的看法正确吗?
看起来另一个答案中的代码可能是从。使用此文件之前检查许可证,但我设法让它读取varint32
使用如下代码:
import sys
import myprotocol_pb2 as proto
import varint # (this is the varint.py file)
data = open("filename.bin", "rb").read() # read file as string
decoder = varint.decodeVarint32 # get a varint32 decoder
# others are available in varint.py
next_pos, pos = 0, 0
while pos < len(data):
msg = proto.Msg() # your message type
next_pos, pos = decoder(data, pos)
msg.ParseFromString(data[pos:pos + next_pos])
# use parsed message
pos += next_pos
print "done!"
这是非常简单的代码,旨在加载由以下分隔的单一类型的消息varint32
s 描述下一条消息的大小。
Update:也可以使用以下命令直接从 protobuf 库包含此文件:
from google.protobuf.internal.decoder import _DecodeVarint32
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)