【问题标题】:Print human friendly Protobuf message打印人类友好的 Protobuf 消息
【发布时间】:2015-11-06 01:28:56
【问题描述】:

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

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

【问题讨论】:

    标签: python protocol-buffers


    【解决方案1】:

    这是在 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;
    }
    

    【讨论】:

    • 有红宝石等价物吗?
    【解决方案2】:

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

    【讨论】:

    • 确实,这行得通。但是,对于我的特定消息描述,对于某些特定的消息内容,消息被打印为空字符串,但我认为这是来自库的错误。
    【解决方案3】:

    正如回答的那样,print 和 __str__ 确实有效,但我不会将它们用于调试字符串之外的任何事情。

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

    【讨论】:

      猜你喜欢
      • 2013-03-22
      • 1970-01-01
      • 2023-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多