使用 Python,如何获取 Google protobuf 消息的二进制序列化?

发布于 2024-08-13 11:36:44 字数 334 浏览 4 评论 0原文

我在 中看到函数 SerializeAsString protobuf Python 文档,但就像这表明的那样,这给了我二进制数据的字符串版本。有没有一种方法可以使用Python序列化和解析protobuf数据的二进制数组?

我们有一个 C++ 应用程序,它将 protobuf 消息作为二进制数据存储在文件中。我们想使用 Python 读取和写入该文件。

I see the function SerializeAsString in the protobuf Python documentation, but like this suggests, this gives me a string version of the binary data. Is there a way of serializing and parsing a binary array of protobuf data using Python?

We have a C++ application that stores the protobuf messages as binary data in a file. We'd like to read and write to the file using Python.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

三五鸿雁 2024-08-20 11:36:45

Python 2(编辑:生命周期结束 2020)字符串可以保存二进制数据,因此 SerializeAsString 返回二进制数据。

编辑:来自注释:“在 Python 3 中,SerializeToString 方法返回字节实例”

Python 2 (edit: end of life 2020) strings can hold binary data, therefore SerializeAsString returns binary data.

Edit: Surfacing from comments: "In Python 3, the SerializeToString method returns an instance of bytes"

奶茶白久 2024-08-20 11:36:45

.serializeToString() 尽管其名称如此,但返回的是 bytes 类型,而不是 str 类型。

造成这种混乱的部分原因是方法名称保持不变,并且他们没有更新文档;你只需要知道当他们说“字符串”时,他们的意思是字节

.serializeToString(), despite its name, returns the bytes type, not the str type.

Part of what makes this confusing is that the method name remains unchanged, and they haven't updated the documentation; you just have to know that when they say "String" they mean bytes.

岁月如刀 2024-08-20 11:36:45

我认为字符串是 Python 中表示二进制数据的常用方式。你到底想做什么?

[编辑]

看看 struct 模块: http://docs.python.org/library /struct.html

I think that strings are the usual way to represent binary data in Python. What do you exactly want to do?

[Edit]

Have a look at the struct module: http://docs.python.org/library/struct.html

独行侠 2024-08-20 11:36:45

您可以使用 Python 字符串来获取原始缓冲区序列化数据(无论它们如何编写 - 使用 Python、Java、C++ 或任何其他语言)。

这些是原始缓冲区教程的 Python 版本中的一行:
address_book.ParseFromString(f.read())

You can use Pythons Strings for getting proto buffers serialized data (doesn't matter how they ware crated - in Python, Java, C++ or any other language).

These is line from Pythons version of proto buffers tutorial:
address_book.ParseFromString(f.read())

家住魔仙堡 2024-08-20 11:36:45

目前尚不清楚您想要做什么:

  1. 使用整个消息的序列化形式执行某些操作(来自 SerializeAsString 方法)。不确定你想用这个做什么?
  2. 将字节字符串存储在 protobuf 消息中 - 只需使用 .proto 文件中的 bytes 类型,并使用 python 中的字节字符串作为变量。

It not clear what you want to do:

  1. Do something with the serialized form of an entire message (From the SerializeAsString method). Not sure what you'd want to do with this?
  2. Store a byte string inside a protobuf message - just use the bytes type in the .proto file, and a byte string in python for the variable.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文