使用 Python,如何获得我的 Google protobuf 消息的二进制序列化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1859438/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using Python, how do I get a binary serialization of my Google protobuf message?
提问by Nick Bolton
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?
我在protobuf Python 文档中看到了函数 SerializeAsString ,但就像这表明的那样,这给了我二进制数据的字符串版本。有没有办法使用 Python 序列化和解析 protobuf 数据的二进制数组?
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.
我们有一个 C++ 应用程序,它将 protobuf 消息作为二进制数据存储在文件中。我们想使用 Python 读取和写入文件。
回答by Nick Bolton
Python strings can hold binary data, therefore SerializeAsString
returns binary data.
Python 字符串可以保存二进制数据,因此SerializeAsString
返回二进制数据。
回答by Bastien Léonard
I think that strings are the usual way to represent binary data in Python. What do you exactly want to do?
我认为字符串是 Python 中表示二进制数据的常用方式。你到底想做什么?
[Edit]
[编辑]
Have a look at the struct module: http://docs.python.org/library/struct.html
回答by Maciek Sawicki
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).
您可以使用 Python 字符串来获取 proto 缓冲区序列化数据(不管它们是如何创建的 - 在 Python、Java、C++ 或任何其他语言中)。
These is line from Pythons version of proto buffers tutorial:
address_book.ParseFromString(f.read())
这些是 Python 版本的 proto 缓冲区教程中的一行:
address_book.ParseFromString(f.read())
回答by Douglas Leeder
It not clear what you want to do:
不清楚你想做什么:
- Do something with the serialized form of an entire message (From the SerializeAsString method). Not sure what you'd want to do with this?
- Store a byte string inside a protobuf message - just use the
bytes
type in the .proto file, and a byte string in python for the variable.
- 对整个消息的序列化形式执行某些操作(来自 SerializeAsString 方法)。不确定你想用它做什么?
- 在 protobuf 消息中存储一个字节字符串 - 只需使用
bytes
.proto 文件中的类型,并在 python 中使用一个字节字符串作为变量。