[英]How to access unknown fields - python protobuf
我正在使用結構相似但不相同的大量消息類型。 這些中所有共同的東西都在另一條消息中。 收到消息時,我將使用常見消息類型對其進行解析。 但是,我似乎找不到一種方法來訪問此類型之外的字段(即非公共字段)。 有沒有辦法訪問python中設置的未知字段?
編輯:我剛剛在文檔中看到了這一點:
“ 如果消息具有未知字段,當前的Java和C ++實現將在順序排列的已知字段之后以任意順序寫入它們。當前的Python實現不會跟蹤未知字段。 ”
這是否意味着如果我使用通用類型進行解析,例如:
proto = msg_pb2.Common() proto.ParseFromString(raw_msg)
消息Common中未定義的任何字段都被丟棄了嗎?
對於尋求答案的人, reflection
模塊可以幫助我: https : //developers.google.com/protocol-buffers/docs/reference/python/google.protobuf.reflection-module
相關示例代碼:
用法示例:
file_descriptor = descriptor_pb2.FileDescriptorProto()
file_descriptor.ParseFromString(proto2_string)
msg_descriptor = descriptor.MakeDescriptor(file_descriptor.message_type[0])
msg_class = reflection.MakeClass(msg_descriptor)
msg = msg_class()
Args:
descriptor: A descriptor.Descriptor object describing the protobuf.
Returns:
The Message class object described by the descriptor.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.