简体   繁体   中英

Replace lines in a protobuf file using python

I have an existing proto file that I would like to change. What I would like to do is read the file in, change a value or two, and then write it back out to disk as a .proto file, to be read by another program. According to this documentation , I should be able to write something like this:

from google.protobuf import message

msg = message.Message()
msg.ParseFromString(infile.read())

... (make changes)

outfile.write(msg.SerializeToString())

But it just gives me a NotImplementedError . Where is the library I need to interface with protobuf text files? This seems to work for C++, why hasn't it been implemented for python? (No, the functions in google.protobuf.text_format aren't implemented either).

You seem to be confusing several different concepts here.

message.Message is an abstract base class. You need to construct an instance of the specific derived class you're interested in.

.proto files contain type definitions, not message data. You must compile your .proto file using protoc , the Protocol Compiler. It will generate Python code which you can then import into your program in order to construct the specific type you want. Please see the Protobuf tutorial for details.

Use ParseFromString() to parse binary protobuf data from a file, and use SerializeToString() to convert the message back into binary data. You should almost always use binary format for protobuf data.

The TextFormat class you reference implements an alternative encoding of protobufs that is human-readable. This format is not recommended for most use cases. If you want a human-readable format, you may be better off with JSON, but it will always be much slower and less-compact than binary encodings. TextFormat is occasionally useful for debugging (printing out a message) and sometimes for writing message data as source code. TextFormat is available in the Python library as the text_format module .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM