Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print human friendly Protobuf message

Tags:

I couldn't find anywhere a possibility to print a human friendly content of a Google Protobuf message.

Is there an equivalent in Python for Java's toString() or C++'s DebugString()?

like image 624
Alexandru Irimiea Avatar asked Nov 06 '15 01:11

Alexandru Irimiea


People also ask

What is Protobuf message?

Protocol Buffers (Protobuf) is a free and open-source cross-platform data format used to serialize structured data. It is useful in developing programs to communicate with each other over a network or for storing data.

How do I view a .proto file?

If you cannot open your PROTO file correctly, try to right-click or long-press the file. Then click "Open with" and choose an application. You can also display a PROTO file directly in the browser: Just drag the file onto this browser window and drop it.


1 Answers

Here's an example for read/write human friendly text file using protobuf 2.0 in python.

from google.protobuf import text_format 

read from a text file

f = open('a.txt', 'r') address_book = addressbook_pb2.AddressBook() # replace with your own message text_format.Parse(f.read(), address_book) f.close() 

write to a text file

f = open('b.txt', 'w') f.write(text_format.MessageToString(address_book)) f.close() 

The c++ equivalent is:

bool ReadProtoFromTextFile(const std::string filename, google::protobuf::Message* proto) {     int fd = _open(filename.c_str(), O_RDONLY);     if (fd == -1)         return false;      google::protobuf::io::FileInputStream* input = new google::protobuf::io::FileInputStream(fd);     bool success = google::protobuf::TextFormat::Parse(input, proto);      delete input;     _close(fd);     return success; }  bool WriteProtoToTextFile(const google::protobuf::Message& proto, const std::string filename) {     int fd = _open(filename.c_str(), O_WRONLY | O_CREAT | O_TRUNC, 0644);     if (fd == -1)         return false;      google::protobuf::io::FileOutputStream* output = new google::protobuf::io::FileOutputStream(fd);     bool success = google::protobuf::TextFormat::Print(proto, output);      delete output;     _close(fd);     return success; } 
like image 199
Neil Z. Shao Avatar answered Sep 28 '22 14:09

Neil Z. Shao