打印人类友好协议

2024-05-16 19:34:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

在Python中是否有一个等价于java的^ {< CD1>}或C++的{{CD2}}?


Tags: 消息内容地方java可能性protobuf等价人性化
3条回答

如果您使用的是protobuf包,print函数/语句将为您提供消息的可读表示,因为^{}方法是:-)。

正如所回答的,print__str__确实有效,但除了调试字符串之外,我不会使用它们。

如果您正在编写用户可以看到的内容,最好使用^{}模块,该模块有更多的控件(例如是否转义UTF8字符串),以及将文本格式解析为protobuf的函数。

下面是一个示例,用于在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;
}

相关问题 更多 >