add_person.py 1.7 KB

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