def main(): # address_book = address_pb2.AddressBook() # person = address_book.people.add() # person.id = 1234 # person.name = "John Doe" # person.email = "*****@*****.**" # phone = person.phones.add() # phone.number = "555-4321" # phone.type = address_pb2.Person.HOME # person2 = address_book.people.add() # person2.id = 3456 # person2.name = "Joe DiNiso" # person2.email = "joseph@" # phone = person2.phones.add() # phone.number = '515231' # phone.type = address_pb2.Person.HOME # with open("./proto.pb", "wb") as f: # f.write(address_book.SerializeToString()) address_book = address_pb2.AddressBook() with open("./proto.pb", "rb") as f: address_book.ParseFromString(f.read()) for person in address_book.people: print(person.name) for phone in person.phones: print(phone.number)
def ListPeople(address_book): for person in address_book.people: print("Person ID:", person.id) print(" Name:", person.name) if person.email != "": print(" E-mail address:", person.email) for phone_number in person.phones: if phone_number.type == address_pb2.Person.MOBILE: print(" Mobile phone #:", ) elif phone_number.type == address_pb2.Person.HOME: print(" Home phone #:", ) elif phone_number.type == address_pb2.Person.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 = address_pb2.AddressBook() # Read the existing address book. with open(sys.argv[1], "rb") as f: address_book.ParseFromString(f.read()) ListPeople(address_book)