Print human friendly Protobuf message

后端 未结 3 976
清歌不尽
清歌不尽 2021-02-18 14:23

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()

相关标签:
3条回答
  • 2021-02-18 14:42

    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;
    }
    
    0 讨论(0)
  • 2021-02-18 15:07

    If you're using the protobuf package, the print function/statement will give you a human-readable representation of the message, because of the __str__ method :-).

    0 讨论(0)
  • 2021-02-18 15:08

    As answered, print and __str__ do work, but I wouldn't use them for anything more than debug strings.

    If you're writing to something that users could see, it's better to use the google.protobuf.text_format module, which has some more controls (e.g. escaping UTF8 strings or not), as well as functions for parsing text-format as protobufs.

    0 讨论(0)
提交回复
热议问题