欢迎访问宙启技术站
智能推送

使用google.protobuf.text_format模块在Python中将文本格式的protobuf消息转换为字典格式的方法

发布时间:2024-01-16 19:47:39

在Python中,可以使用google.protobuf.text_format模块将文本格式的protobuf消息转换为字典格式。下面是一个使用例子:

假设我们有以下的protobuf定义文件 message.proto

syntax = "proto3";

message Person {
  string name = 1;
  int32 age = 2;
  repeated string phone_numbers = 3;
}

根据该定义文件生成protobuf代码:

$ protoc --python_out=. message.proto

然后,我们创建一个Python脚本来读取文本格式的protobuf消息并将其转换为字典格式。

import google.protobuf.text_format as text_format
from message_pb2 import Person

# 读取文本格式的protobuf消息
protobuf_text = """
name: "John Doe"
age: 30
phone_numbers: "1234567890"
phone_numbers: "0987654321"
"""

# 创建一个空白的Person对象
person = Person()

# 将文本格式的protobuf消息解析为Person对象
text_format.Parse(protobuf_text, person)

# 将Person对象转换为字典
person_dict = {
    'name': person.name,
    'age': person.age,
    'phone_numbers': list(person.phone_numbers)
}

# 打印转换后的字典格式
print(person_dict)

运行上述代码将输出:

{'name': 'John Doe', 'age': 30, 'phone_numbers': ['1234567890', '0987654321']}

通过使用text_format.Parse()方法,我们可以将文本格式的protobuf消息解析为对应的protobuf对象。然后,我们可以访问该对象的属性,并将属性的值存储到字典中。这样我们就能够以字典的形式操作protobuf消息的内容。