protobuf/examples/list_people.py

41 lines
1.2 KiB
Python
Raw Normal View History

2015-04-12 03:23:45 +00:00
#! /usr/bin/env python
2008-07-10 02:12:20 +00:00
# See README.txt for information and build instructions.
from __future__ import print_function
2008-07-10 02:12:20 +00:00
import addressbook_pb2
import sys
2008-07-10 02:12:20 +00:00
# Iterates though all people in the AddressBook and prints info about them.
def ListPeople(address_book):
2015-07-20 22:24:08 +00:00
for person in address_book.people:
print("Person ID:", person.id)
print(" Name:", person.name)
2015-07-20 21:34:27 +00:00
if person.email != "":
print(" E-mail address:", person.email)
2008-07-10 02:12:20 +00:00
2015-07-20 21:34:27 +00:00
for phone_number in person.phones:
2008-07-10 02:12:20 +00:00
if phone_number.type == addressbook_pb2.Person.MOBILE:
print(" Mobile phone #:", end=" ")
2008-07-10 02:12:20 +00:00
elif phone_number.type == addressbook_pb2.Person.HOME:
print(" Home phone #:", end=" ")
2008-07-10 02:12:20 +00:00
elif phone_number.type == addressbook_pb2.Person.WORK:
print(" Work phone #:", end=" ")
print(phone_number.number)
2008-07-10 02:12:20 +00:00
# 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")
2008-07-10 02:12:20 +00:00
sys.exit(-1)
address_book = addressbook_pb2.AddressBook()
# Read the existing address book.
2016-01-25 22:43:31 +00:00
with open(sys.argv[1], "rb") as f:
address_book.ParseFromString(f.read())
2008-07-10 02:12:20 +00:00
ListPeople(address_book)