Writing A Message
Now let's try using your protocol buffer classes. The first thing you want your address book application to be able to do is write personal details to your address book file. To do this, you need to create and populate instances of your protocol buffer classes and then write them to an output stream.
Here is a program which reads an
AddressBookfrom a file, adds one newPersonto it based on user input, and writes the newAddressBookback out to the file again. The parts which directly call or reference code generated by the protocol compiler are highlighted.
python test.py addressbook.protoTraceback (most recent call last):File "test.py", line 56, in <module>address_book.ParseFromString(f.read())File "/Users/junhao.wen/anaconda2/lib/python2.7/site-packages/protobuf-3.1.0-py2.7.egg/google/protobuf/message.py", line 185, in ParseFromStringself.MergeFromString(serialized)File "/Users/junhao.wen/anaconda2/lib/python2.7/site-packages/protobuf-3.1.0-py2.7.egg/google/protobuf/internal/python_message.py", line 1087, in MergeFromStringif self._InternalParse(serialized, 0, length) != length:File "/Users/junhao.wen/anaconda2/lib/python2.7/site-packages/protobuf-3.1.0-py2.7.egg/google/protobuf/internal/python_message.py", line 1113, in InternalParsenew_pos = local_SkipField(buffer, new_pos, end, tag_bytes)File "/Users/junhao.wen/anaconda2/lib/python2.7/site-packages/protobuf-3.1.0-py2.7.egg/google/protobuf/internal/decoder.py", line 850, in SkipFieldreturn WIRETYPE_TO_SKIPPER[wire_type](buffer, pos, end)File "/Users/junhao.wen/anaconda2/lib/python2.7/site-packages/protobuf-3.1.0-py2.7.egg/google/protobuf/internal/decoder.py", line 799, in _SkipGroupnew_pos = SkipField(buffer, pos, end, tag_bytes)File "/Users/junhao.wen/anaconda2/lib/python2.7/site-packages/protobuf-3.1.0-py2.7.egg/google/protobuf/internal/decoder.py", line 850, in SkipFieldreturn WIRETYPE_TO_SKIPPER[wire_type](buffer, pos, end)File "/Users/junhao.wen/anaconda2/lib/python2.7/site-packages/protobuf-3.1.0-py2.7.egg/google/protobuf/internal/decoder.py", line 820, in _RaiseInvalidWireTyperaise _DecodeError('Tag had invalid wire type.')google.protobuf.message.DecodeError: Tag had invalid wire type.
addressbook_pb2.py