首先定义出地址薄:
syntax = "proto2";
package tutorial;
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phones = 4;
}
message AddressBook {
repeated Person people = 1;
}
对于protobuf的对象写方法在百度里面很多,我就不加赘述了,重点是比较少的读取的方法,直接上代码:
#! /usr/bin/python
import addressbook_pb2
import sys
# Iterates though all people in the AddressBook and prints info about them.
def ListPeople(address_book):
for person in address_book.people:
print "Person ID:", person.id
print " Name:", person.name
if person.HasField('email'):
print " E-mail address:", person.email
for phone_number in person.phones:
if phone_number.type == addressbook_pb2.Person.PhoneType.MOBILE:
print " Mobile phone #: ",
elif phone_number.type == addressbook_pb2.Person.PhoneType.HOME:
print " Home phone #: ",
elif phone_number.type == addressbook_pb2.Person.PhoneType.WORK:
print " Work phone #: ",
print phone_number.number
# Main procedure: Reads the entire address book from a file and prints all
# the information inside.
if len(sys.argv) != 2:
print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
sys.exit(-1)
address_book = addressbook_pb2.AddressBook()
# Read the existing address book.
f = open(sys.argv[1], "rb")
address_book.ParseFromString(f.read())
f.close()
ListPeople(address_book)
可以看到从文件里面读取string,利用parsefromstring方法还原出message对象,然后对于repeated的属性可以直接利用for循环进行遍历读取,从实际方法上看是很容易的,但是由于protbuf编译出的.py文件里面并没有生成api接口,而是只有DESCRIPTOR,这样就和C++和java版本不同,如果不熟悉python很难从.py文件里面找到对应的方法,所以在这里做做记录