Using Python, how do I get a binary serialization of my Google protobuf message?
-
13-09-2019 - |
Question
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.
Solution
Python strings can hold binary data, therefore SerializeAsString
returns binary data.
OTHER TIPS
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
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.
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())