Python 打印人类友好的 Protobuf 消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33557965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 13:33:43  来源:igfitidea点击:

Print human friendly Protobuf message

pythonprotocol-buffers

提问by Alexandru Irimiea

I couldn't find anywhere a possibility to print a human friendly content of a Google Protobuf message.

我找不到任何地方可以打印 Google Protobuf 消息的人类友好内容。

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

Python 中是否有 JavatoString()或 C++的等价物DebugString()

采纳答案by cdonts

If you're using the protobufpackage, the printfunction/statement will give you a human-readable representation of the message, because of the __str__method :-).

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

回答by Rafael Lerm

As answered, printand __str__do work, but I wouldn't use them for anything more than debug strings.

正如回答的那样,print并且__str__可以工作,但除了调试字符串之外,我不会将它们用于任何其他用途。

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

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

回答by Neil Z. Shao

Here's an example for read/write human friendlytext file using protobuf 2.0in python.

这是在python 中使用的读/写人类友好文本文件的示例。protobuf 2.0

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:

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