/thirdparty/breakpad/third_party/protobuf/protobuf/examples/add_person.py

http://github.com/tomahawk-player/tomahawk · Python · 58 lines · 37 code · 12 blank · 9 comment · 10 complexity · ea0267adf2f2d7f430aa19d8c37a6901 MD5 · raw file

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