Ale*_*iea 17 python protocol-buffers
我找不到任何可能打印Google Protobuf消息的人性化内容的可能性.
在Java toString()或C++中是否存在Python的等价物DebugString()?
小智 23
这是在python中使用的读/写人类友好文本文件的示例.protobuf 2.0
from google.protobuf import text_format
Run Code Online (Sandbox Code Playgroud)
从文本文件中读取
f = open('a.txt', 'r')
address_book = addressbook_pb2.AddressBook() # replace with your own message
text_format.Parse(f.read(), address_book)
f.close()
Run Code Online (Sandbox Code Playgroud)
写入文本文件
f = open('b.txt', 'w')
f.write(text_format.MessageToString(address_book))
f.close()
Run Code Online (Sandbox Code Playgroud)
在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;
}
Run Code Online (Sandbox Code Playgroud)
正如所回答的,print并且__str__确实有效,但除了调试字符串之外,我不会将它们用于任何其他用途。
如果您要编写用户可以看到的内容,最好使用该google.protobuf.text_format模块,该模块具有更多控件(例如是否转义 UTF8 字符串)以及将文本格式解析为 protobuf 的函数。