在python中,对protobuf对象的元素进行更改的最优雅的方式是什么?
表示protobuf对象的:在python中,对protobuf对象的元素进行更改的最优雅的方式是什么?,python,protocol-buffers,protobuf-python,Python,Protocol Buffers,Protobuf Python,表示protobuf对象的: model { faster_rcnn { num_classes: 37 image_resizer { keep_aspect_ratio_resizer { min_dimension: 600 max_dimension: 1024 } } ... 我希望使用python将其读入对象,对某些值进行一些更改,然后将其写回配置文件 一个复杂的因素是,这是一个相当大的对象
model {
faster_rcnn {
num_classes: 37
image_resizer {
keep_aspect_ratio_resizer {
min_dimension: 600
max_dimension: 1024
}
}
...
我希望使用python将其读入对象,对某些值进行一些更改,然后将其写回配置文件
一个复杂的因素是,这是一个相当大的对象,由许多.proto文件构造而成
我可以通过将protobuf转换为字典,进行编辑,然后再转换回protobuf来完成任务,如下所示:
import tensorflow as tf
from google.protobuf.json_format import MessageToDict
from google.protobuf.json_format import ParseDict
from google.protobuf import text_format
from object_detection.protos import pipeline_pb2
def get_configs_from_pipeline_file(pipeline_config_path, config_override=None):
'''
read .config and convert it to proto_buffer_object
'''
pipeline_config = pipeline_pb2.TrainEvalPipelineConfig()
with tf.gfile.GFile(pipeline_config_path, "r") as f:
proto_str = f.read()
text_format.Merge(proto_str, pipeline_config)
if config_override:
text_format.Merge(config_override, pipeline_config)
return pipeline_config
configs = get_configs_from_pipeline_file('faster_rcnn_resnet101_pets.config')
d = MessageToDict(configs)
d['model']['fasterRcnn']['numClasses']=999
config2 = pipeline_pb2.TrainEvalPipelineConfig()
c = ParseDict(d, config2)
s = text_format.MessageToString(c)
with open('/path/test.config', 'w+') as fh:
fh.write(str(s))
我希望能够直接对protobuf对象进行编辑,而不必转换为字典。然而,问题是,不清楚如何“遍历dom”以发现对我想要更改其值的变量的正确引用。当涉及多个.proto文件时尤其如此
我可以这样编辑,但我希望有更好的方法:
configs.model.ListFields()[0][1].num_classes = 99