打印人性化的Protobuf消息

时间:2015-11-06 01:28:57

标签: python protocol-buffers

我无法在任何地方找到打印Google Protobuf消息的人性化内容的可能性。

Python的toString()还是C ++的DebugString()是否有相应的内容?

3 个答案:

答案 0 :(得分:19)

以下是 python 中使用protobuf 2.0读/写人性化文本文件的示例。

from google.protobuf import text_format

从文本文件中读取

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

写入文本文件

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

c ++ 等价物是:

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

答案 1 :(得分:9)

如果您正在使用protobuf包,print函数/语句将为您提供人类可读的消息表示,因为__str__方法:-)。

答案 2 :(得分:3)

如上所述,print__str__可以正常工作,但我不会将它们用于调试字符串以外的任何内容。

如果你正在写一些用户可以看到的内容,那么最好使用google.protobuf.text_format模块,它有更多控件(例如,转义UTF8字符串),以及用于将文本格式解析为protobufs的函数。

相关问题