我無法找到任何地方打印Google Protobuf消息的人性化內容的可能性。打印人性化Protobuf消息
Python中是否存在與Java的toString()
或C++的DebugString()
等價的?
我無法找到任何地方打印Google Protobuf消息的人性化內容的可能性。打印人性化Protobuf消息
Python中是否存在與Java的toString()
或C++的DebugString()
等價的?
回答時,print
和__str__
可以工作,但除了調試字符串之外,我不會使用它們。
如果你正在寫一些用戶可以看到的東西,最好使用google.protobuf.text_format
模塊,它有更多的控件(例如轉義或不轉義UTF8字符串)以及將文本格式解析爲protobufs的函數。
下面是一個讀寫示例人性化的使用protobuf 2.0
的文本文件python。從文本文件
f = open('a.txt', 'r')
address_book = addressbook_pb2.AddressBook() # replace with your own message
text_format.Parse(f.read(), address_book)
f.close()
寫
from google.protobuf import text_format
讀取到一個文本文件
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;
}
事實上,這個工程。但是,對於我特定的消息描述,對於某些特定的消息內容,消息被打印爲空字符串,但我認爲這是來自庫的錯誤。 –