Source release 14.1.0
This commit is contained in:
29
third_party/protobuf/examples/add_person.py
vendored
29
third_party/protobuf/examples/add_person.py
vendored
@@ -1,10 +1,16 @@
|
||||
#! /usr/bin/python
|
||||
#! /usr/bin/env python
|
||||
|
||||
# See README.txt for information and build instructions.
|
||||
|
||||
import addressbook_pb2
|
||||
import sys
|
||||
|
||||
try:
|
||||
raw_input # Python 2
|
||||
except NameError:
|
||||
raw_input = input # Python 3
|
||||
|
||||
|
||||
# This function fills in a Person message based on user input.
|
||||
def PromptForAddress(person):
|
||||
person.id = int(raw_input("Enter person ID number: "))
|
||||
@@ -19,7 +25,7 @@ def PromptForAddress(person):
|
||||
if number == "":
|
||||
break
|
||||
|
||||
phone_number = person.phone.add()
|
||||
phone_number = person.phones.add()
|
||||
phone_number.number = number
|
||||
|
||||
type = raw_input("Is this a mobile, home, or work phone? ")
|
||||
@@ -30,29 +36,28 @@ def PromptForAddress(person):
|
||||
elif type == "work":
|
||||
phone_number.type = addressbook_pb2.Person.WORK
|
||||
else:
|
||||
print "Unknown phone type; leaving as default value."
|
||||
print("Unknown phone type; leaving as default value.")
|
||||
|
||||
|
||||
# Main procedure: Reads the entire address book from a file,
|
||||
# adds one person based on user input, then writes it back out to the same
|
||||
# file.
|
||||
if len(sys.argv) != 2:
|
||||
print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
|
||||
print("Usage:", sys.argv[0], "ADDRESS_BOOK_FILE")
|
||||
sys.exit(-1)
|
||||
|
||||
address_book = addressbook_pb2.AddressBook()
|
||||
|
||||
# Read the existing address book.
|
||||
try:
|
||||
f = open(sys.argv[1], "rb")
|
||||
address_book.ParseFromString(f.read())
|
||||
f.close()
|
||||
with open(sys.argv[1], "rb") as f:
|
||||
address_book.ParseFromString(f.read())
|
||||
except IOError:
|
||||
print sys.argv[1] + ": File not found. Creating a new file."
|
||||
print(sys.argv[1] + ": File not found. Creating a new file.")
|
||||
|
||||
# Add an address.
|
||||
PromptForAddress(address_book.person.add())
|
||||
PromptForAddress(address_book.people.add())
|
||||
|
||||
# Write the new address book back to disk.
|
||||
f = open(sys.argv[1], "wb")
|
||||
f.write(address_book.SerializeToString())
|
||||
f.close()
|
||||
with open(sys.argv[1], "wb") as f:
|
||||
f.write(address_book.SerializeToString())
|
||||
|
||||
Reference in New Issue
Block a user