Bit*_*iot 3 python introspection protocol-buffers argparse
我有一个谷歌协议缓冲区定义,看起来像跟随:
message Foo {
required string Name = 1;
optional string Address = 2;
optional string NickName = 3;
optional int32 height = 4;
}
Run Code Online (Sandbox Code Playgroud)
现在在python中,我想列出上面的所有属性,但只列出那些属性.但是,交互式python,我看到谷歌定义了更多的字段.所以这似乎有问题.
我已经看了一些关于内省的stackoverflow帖子.有一个看起来不错的检查模块,但问题是谷歌协议缓冲区为我定义的其他成员.
有办法吗?
这就是我想做的事情.我有一个python实用程序,从命令行填写上述字段.我使用argparse,我会:
parser = argparse.ArgumentParser(...)
parser.add_argument( "--attribute_name", blah)
Run Code Online (Sandbox Code Playgroud)
我想将add_argument()放在循环中,并根据proto文件定义使其动态化.基本上,每次我更改proto文件时,我都不想继续修改实用程序的代码.好像我应该能够在python中做到这一点.我只是不知道如何.
有人有建议吗?
谢谢.
有关其他信息,我采用上面的示例,并使用protoc编译它.这是交互式输出:
>>> import hello_pb2
>>> h = hello_pb2.Foo()
>>> dir(h)
['ADDRESS_FIELD_NUMBER', 'Address', 'ByteSize', 'Clear', 'ClearExtension', 'ClearField', 'CopyFrom', 'DESCRIPTOR', 'FindInitializationErrors', 'FromString', 'HEIGHT_FIELD_NUMBER', 'HasExtension', 'HasField', 'IsInitialized', 'ListFields', 'MergeFrom', 'MergeFromString', 'NAME_FIELD_NUMBER', 'NICKNAME_FIELD_NUMBER', 'Name', 'NickName', 'ParseFromString', 'RegisterExtension', 'SerializePartialToString', 'SerializeToString', 'SetInParent', '_InternalParse', '_InternalSerialize', '_Modified', '_SetListener', '__class__', '__deepcopy__', '__delattr__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__metaclass__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__slots__', '__str__', '__subclasshook__', '__unicode__', '__weakref__', '_cached_byte_size', '_cached_byte_size_dirty', '_decoders_by_tag', '_extensions_by_name', '_extensions_by_number', '_fields', '_is_present_in_parent', '_listener', '_listener_for_children', 'height']
Run Code Online (Sandbox Code Playgroud)
我想到了像_fields这样有前途的领域,但那是空的.
答案如下 :(由Kenton Varda回复)
import hello_pb2
h = hello_pb2.Foo()
f = hello_pb2.Foo()
f.DESCRIPTOR.fields_by_name.keys()
Run Code Online (Sandbox Code Playgroud)
你想要迭代Foo.DESCRIPTOR.fields.看Descriptor课程:
每个消息类都有一个静态成员DESCRIPTOR,它是该类型的描述符.