protobuf TextFormat question: Parsing TextFormat into message [fixed]

1,299 views
Skip to first unread message

Kevin

unread,
Feb 6, 2012, 7:14:34 PM2/6/12
to Protocol Buffers
...previous message didn't have example code sanitized and probably
doesn't make sense. Please delete/ignore previous and use this one. :)

Hard to find much high-level documentation on using TextFormat, but
for some Python protobuf work I'm doing, the text format is much
easier to read (and easier to organize into test vector files) in the
protobuf text format, rather than manipulating the python objects
manually.

(I've changed message types/contents to generalize, please forgive any
typos, this isn't the real code)

my_envelope.proto (this file gets sent through protoc to generate
Python code):
message MyEnvelope {
optional InnerMessage innerMessage = 1;
}

and I have a test message that I'd like to take from TextFormat and
put into a protobuf message structure:
innerMessage {
value1: 100
value2: 200
}

I have found that I can get it to work in python using

from google.protobuf import text_format
import my_envelope_pb2
my_msg = my_envelope_pb2.MyEnvelope()
text_format.Merge("""
innerMessage {
value1: 100
value2: 200
}
""", my_msg)

But I guess my question is this- is there a preferred way to do this?
I had originally expected that ParseFromString would figure out that
this was an ASCII representation and call Merge appropriately.
i.e. I had expected the following would work
import my_envelope_pb2
my_msg = my_envelope_pb2.MyEnvelope()
my_msg.ParseFromString("""
inner {
value1: 100
value2: 200
}
""")
but from the errors it appeared that ParseFromString only deals with
string containers for binary format. Is this the case? Just trying to
make sure I'm not calling Merge at an innapropriate/strange layer when
some high-level call exists. As I mentioned, documentation on text
format is somewhat thin, so this is the best I could piece together
from API info. Thanks!

Jeremiah Jordan

unread,
Feb 29, 2012, 9:21:55 PM2/29/12
to prot...@googlegroups.com
Are you actually reading these values from a file?  If not, why don't you just:

my_msg = my_envelope_pb2.MyEnvelope() 
my_msg.InnerMessage.value1 = 100
my_msg.InnerMessage.value2 = 200

You are correct that ParseFromString just reads back the output of SerializeToString
Reply all
Reply to author
Forward
0 new messages