使用 Python,如何获取 Google protobuf 消息的二进制序列化?
我在 中看到函数 SerializeAsString protobuf Python 文档,但就像这表明的那样,这给了我二进制数据的字符串版本。有没有一种方法可以使用Python序列化和解析protobuf数据的二进制数组?
我们有一个 C++ 应用程序,它将 protobuf 消息作为二进制数据存储在文件中。我们想使用 Python 读取和写入该文件。
I see the function SerializeAsString in the protobuf Python documentation, but like this suggests, this gives me a string version of the binary data. Is there a way of serializing and parsing a binary array of protobuf data using Python?
We have a C++ application that stores the protobuf messages as binary data in a file. We'd like to read and write to the file using Python.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Python 2(编辑:生命周期结束 2020)字符串可以保存二进制数据,因此
SerializeAsString
返回二进制数据。编辑:来自注释:“在 Python 3 中,
SerializeToString
方法返回字节实例”Python 2 (edit: end of life 2020) strings can hold binary data, therefore
SerializeAsString
returns binary data.Edit: Surfacing from comments: "In Python 3, the
SerializeToString
method returns an instance of bytes".serializeToString()
尽管其名称如此,但返回的是bytes
类型,而不是str
类型。造成这种混乱的部分原因是方法名称保持不变,并且他们没有更新文档;你只需要知道当他们说“字符串”时,他们的意思是
字节
。.serializeToString()
, despite its name, returns thebytes
type, not thestr
type.Part of what makes this confusing is that the method name remains unchanged, and they haven't updated the documentation; you just have to know that when they say "String" they mean
bytes
.我认为字符串是 Python 中表示二进制数据的常用方式。你到底想做什么?
[编辑]
看看 struct 模块: http://docs.python.org/library /struct.html
I think that strings are the usual way to represent binary data in Python. What do you exactly want to do?
[Edit]
Have a look at the struct module: http://docs.python.org/library/struct.html
您可以使用 Python 字符串来获取原始缓冲区序列化数据(无论它们如何编写 - 使用 Python、Java、C++ 或任何其他语言)。
这些是原始缓冲区教程的 Python 版本中的一行:
address_book.ParseFromString(f.read())
You can use Pythons Strings for getting proto buffers serialized data (doesn't matter how they ware crated - in Python, Java, C++ or any other language).
These is line from Pythons version of proto buffers tutorial:
address_book.ParseFromString(f.read())
目前尚不清楚您想要做什么:
It not clear what you want to do:
bytes
type in the .proto file, and a byte string in python for the variable.