gpt4 book ai didi

python - 打印人类友好的 Protobuf 消息

转载 作者:IT老高 更新时间:2023-10-28 21:17:48 26 4
gpt4 key购买 nike

我找不到任何可以打印 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;
}

关于python - 打印人类友好的 Protobuf 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33557965/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com