打印人类友好的 Protobuf 消息

Print human friendly Protobuf message

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

Python 中是否有 Java 的 toString() 或 C++ 的 DebugString() 的等价物?

如果您使用 protobuf package, the print function/statement will give you a human-readable representation of the message, because of the __str__ 方法 :-).

正如回答的那样,print__str__ 确实有效,但我不会将它们用于除调试字符串以外的任何用途。

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

下面是 read/write人性化 文本文件的示例,在 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;
}