问题
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.
回答1:
Python strings can hold binary data, therefore SerializeAsString
returns binary data.
回答2:
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
回答3:
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.
回答4:
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())
来源:https://stackoverflow.com/questions/1859438/using-python-how-do-i-get-a-binary-serialization-of-my-google-protobuf-message