1

I have proto message that I need to attach a string containing information about the data (units, scaling factor etc). I am using custom options as per the proto2 guide. I also have attempted to follow a previous question where they printed custom options for 1 message here. I would like to print out all fields from the message along side the string. I have been struggling to find a solution, so far what i have tried is:

In my .proto file: The Service message contains fields that are themselves messages such as 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;
    ...
}

Then in the python file,how would iterate over each field in Service and the nested message My_Message to retrieve both its value and also then extract the 'formatting_stuff'.

This is my attempt, but I can not get the field options to print the custom options:

messanger.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)

The terminal output is:

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:

As you can see, my custom fields are not being printed. Please could you assist me with printing out the custom options.

Kind regards

rhino123
  • 11
  • 1
  • On a cursory look, your code appears to be correct. It might help if you can provide a full, runnable piece of code. – jpa Jan 14 '20 at 07:21

0 Answers0