【发布时间】:2015-11-06 01:28:56
【问题描述】:
我找不到任何可以打印 Google Protobuf 消息的人性化内容的可能性。
在 Python 中是否有 Java 的 toString() 或 C++ 的 DebugString() 的等价物?
【问题讨论】:
我找不到任何可以打印 Google Protobuf 消息的人性化内容的可能性。
在 Python 中是否有 Java 的 toString() 或 C++ 的 DebugString() 的等价物?
【问题讨论】:
这是在 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;
}
【讨论】:
正如回答的那样,print 和 __str__ 确实有效,但我不会将它们用于调试字符串之外的任何事情。
如果您正在写入用户可以看到的内容,最好使用 google.protobuf.text_format 模块,该模块具有更多控件(例如是否转义 UTF8 字符串)以及将文本格式解析为 protobufs 的函数.
【讨论】: