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