blob: aa0fbca7375dfd64cb4dfb2b64bf08ca28aba288 [file] [log] [blame]
Brian Silverman9c614bc2016-02-15 20:20:02 -05001#! /usr/bin/env python
2
3# See README.txt for information and build instructions.
4
5import addressbook_pb2
6import sys
7
Austin Schuh40c16522018-10-28 20:27:54 -07008try:
9 raw_input # Python 2
10except NameError:
11 raw_input = input # Python 3
12
13
Brian Silverman9c614bc2016-02-15 20:20:02 -050014# This function fills in a Person message based on user input.
15def PromptForAddress(person):
16 person.id = int(raw_input("Enter person ID number: "))
17 person.name = raw_input("Enter name: ")
18
19 email = raw_input("Enter email address (blank for none): ")
20 if email != "":
21 person.email = email
22
23 while True:
24 number = raw_input("Enter a phone number (or leave blank to finish): ")
25 if number == "":
26 break
27
28 phone_number = person.phones.add()
29 phone_number.number = number
30
31 type = raw_input("Is this a mobile, home, or work phone? ")
32 if type == "mobile":
33 phone_number.type = addressbook_pb2.Person.MOBILE
34 elif type == "home":
35 phone_number.type = addressbook_pb2.Person.HOME
36 elif type == "work":
37 phone_number.type = addressbook_pb2.Person.WORK
38 else:
Austin Schuh40c16522018-10-28 20:27:54 -070039 print("Unknown phone type; leaving as default value.")
40
Brian Silverman9c614bc2016-02-15 20:20:02 -050041
42# Main procedure: Reads the entire address book from a file,
43# adds one person based on user input, then writes it back out to the same
44# file.
45if len(sys.argv) != 2:
Austin Schuh40c16522018-10-28 20:27:54 -070046 print("Usage:", sys.argv[0], "ADDRESS_BOOK_FILE")
Brian Silverman9c614bc2016-02-15 20:20:02 -050047 sys.exit(-1)
48
49address_book = addressbook_pb2.AddressBook()
50
51# Read the existing address book.
52try:
53 with open(sys.argv[1], "rb") as f:
54 address_book.ParseFromString(f.read())
55except IOError:
Austin Schuh40c16522018-10-28 20:27:54 -070056 print(sys.argv[1] + ": File not found. Creating a new file.")
Brian Silverman9c614bc2016-02-15 20:20:02 -050057
58# Add an address.
59PromptForAddress(address_book.people.add())
60
61# Write the new address book back to disk.
62with open(sys.argv[1], "wb") as f:
63 f.write(address_book.SerializeToString())