首页 > 解决方案 > Python:打印所有协议缓冲区字段选项

问题描述

我有原始消息,我需要附加一个字符串,其中包含有关数据的信息(单位、比例因子等)。我按照proto2 指南使用自定义选项。我还尝试关注之前的问题,他们在此处打印了 1 条消息的自定义选项。我想在字符串旁边打印出消息中的所有字段。我一直在努力寻找解决方案,到目前为止我尝试过的是:

在我的 .proto 文件中:Service 消息包含本身就是消息的字段,例如 My_Message。

import "google/protobuf/descriptor.proto";

extend google.protobuf.FieldOptions {
   optional string formatting_stuff = 50000;
}

message My_Message
{
    optional uint32 base_frequency_hz = 1 [(formatting_stuff) = "test"];
    optional float trigger_frequency_hz = 2 [(formatting_stuff) = "test2"];
    ...
}

message Service
{
    optional My_Message x = 13;
    ...
}

然后在 python 文件中,如何遍历 Service 中的每个字段和嵌套消息 My_Message 以检索其值,然后提取“formatting_stuff”。

这是我的尝试,但我无法获取打印自定义选项的字段选项:

信使.py

   ...
   rsp = self.proto.Service().FromString(self.data)

   desc = protobuf_file.Service.My_Message.DESCRIPTOR
   for rsp_field in response.DESCRIPTOR.fields:
       print("Response Field  name: ", rsp_field.name)
       print("Response Field  value: ", getattr(rsp, rsp_field.name))

       options = desc.GetOptions()
       formatting = options.Extensions[protobuf_file.formatting_stuff]
       print("Response Field formatting: ", formatting)

终端输出为:

Response Field  name:  base_frequency_hz 
Response Field  value:  720000
Response Field formatting:

Response Field  name:  trigger_frequency_hz 
Response Field  value:  3000.0
Response Field formatting:

如您所见,我的自定义字段没有被打印。请您帮我打印出自定义选项。

亲切的问候

标签: pythonprotocol-buffers

解决方案


推荐阅读