Print human friendly message Protobuf

I couldn’t find anywhere else to print the human-friendly content of a Google Protobuf message.

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

+4
source share
3 answers

If you use the protobuf package , the function operator printwill provide you with a human- readable view due to the method :-)__str__ .

+4
source

Here is an example for reading / writing a friendly person 's text file using protobuf 2.0in python .

from google.protobuf import text_format

reading 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 text file

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

++:

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;
}
+4

, print __str__ , , .

If you write something that users could see, it is better to use a module google.protobuf.text_formatthat contains several controls (for example, escaping UTF8 strings or not), as well as functions for parsing a text format in the form of protobuffs.

+2
source

Source: https://habr.com/ru/post/1614670/


All Articles