如何获取python protobuf消息的枚举字段的值名称

mih*_*icc 9 python enums protocol-buffers

我还没有进入 protobuf,但我会尝试提出一个问题。鉴于我有:

  enum SourceType {
     WEB = 1;
  }
  message Message {
    optional SourceType source = 6;
  }
Run Code Online (Sandbox Code Playgroud)

我有消息,它是 Message 的一个实例,我想像打印消息一样获取源的值。但是做 message.source 给了我代码。我只想从对象中获取值,而不是使用其他枚举/映射/常量。在最后一行中,我有一个如何达到预期值的示例,但我正在寻找一种更优雅的方式。

  > message    
  <Message_pb2.Message object at 0x7f78561a83c8>
  > print message
  source: WEB
  > print message.source 
  1
  > message.DESCRIPTOR.fields_by_name['source'].enum_type.values_by_number[1].name 
  WEB
Run Code Online (Sandbox Code Playgroud)

小智 5

EnumTypeWrapper类有一个Name方法,它返回一个的名称enmum的值。所以在这种情况下,导入SourceTypefrom 后Message_pb2SourceType.Name()将返回值的名称。


Ken*_*rda 1

我相信使用EnumDescriptor您在示例中所做的操作是获取枚举值名称的唯一方法。当然,您可以围绕它编写一个辅助函数以使其不那么冗长。