2024-05-19 06:47:26 发布
网友
我在任何地方都找不到打印谷歌Protobuf消息中人性化内容的可能性。
在Python中是否有一个等价于java的^ {< CD1>}或C++的{{CD2}}?
如果您使用的是protobuf包,print函数/语句将为您提供消息的可读表示,因为^{}方法是:-)。
print
正如所回答的,print和__str__确实有效,但除了调试字符串之外,我不会使用它们。
__str__
如果您正在编写用户可以看到的内容,最好使用^{}模块,该模块有更多的控件(例如是否转义UTF8字符串),以及将文本格式解析为protobuf的函数。
下面是一个示例,用于在python中使用protobuf 2.0读取/写入对人类友好的文本文件。
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; }
如果您使用的是protobuf包,} 方法是:-)。
print
函数/语句将为您提供消息的可读表示,因为^{正如所回答的,
print
和__str__
确实有效,但除了调试字符串之外,我不会使用它们。如果您正在编写用户可以看到的内容,最好使用^{} 模块,该模块有更多的控件(例如是否转义UTF8字符串),以及将文本格式解析为protobuf的函数。
下面是一个示例,用于在python中使用
protobuf 2.0
读取/写入对人类友好的文本文件。从文本文件中读取
写入文本文件
c++等价物是:
相关问题 更多 >
编程相关推荐