pycapnp/examples/example.py

65 lines
1.8 KiB
Python
Raw Normal View History

2013-07-07 02:31:50 -07:00
from __future__ import print_function
import os
import capnp
2013-07-07 02:31:50 -07:00
this_dir = os.path.dirname(__file__)
addressbook = capnp.load(os.path.join(this_dir, 'addressbook.capnp'))
def writeAddressBook(fd):
message = capnp.MallocMessageBuilder()
addressBook = message.initRoot(addressbook.AddressBook)
2013-07-07 13:00:03 -07:00
people = addressBook.init('people', 2)
alice = people[0]
alice.id = 123
alice.name = 'Alice'
alice.email = 'alice@example.com'
2013-07-07 13:00:03 -07:00
alicePhones = alice.init('phones', 1)
alicePhones[0].number = "555-1212"
alicePhones[0].type = 'mobile'
alice.employment.school = "MIT"
bob = people[1]
bob.id = 456
bob.name = 'Bob'
bob.email = 'bob@example.com'
2013-07-07 13:00:03 -07:00
bobPhones = bob.init('phones', 2)
bobPhones[0].number = "555-4567"
bobPhones[0].type = 'home'
2013-07-07 02:31:50 -07:00
bobPhones[1].number = "555-7654"
bobPhones[1].type = 'work'
bob.employment.unemployed = None
capnp.writePackedMessageToFd(fd, message)
2013-07-07 02:31:50 -07:00
def printAddressBook(fd):
message = capnp.PackedFdMessageReader(f.fileno())
addressBook = message.getRoot(addressbook.AddressBook)
for person in addressBook.people:
2013-07-07 02:31:50 -07:00
print(person.name, ':', person.email)
for phone in person.phones:
2013-07-07 02:31:50 -07:00
print(phone.type, ':', phone.number)
which = person.employment.which()
2013-07-07 02:31:50 -07:00
print(which)
if which == 'unemployed':
2013-07-07 02:31:50 -07:00
print('unemployed')
elif which == 'employer':
2013-07-07 02:31:50 -07:00
print('employer:', person.employment.employer)
elif which == 'school':
2013-07-07 02:31:50 -07:00
print('student at:', person.employment.school)
elif which == 'selfEmployed':
2013-07-07 02:31:50 -07:00
print('self employed')
print()
2013-07-07 13:00:03 -07:00
if __name__ == '__main__':
f = open('example', 'w')
writeAddressBook(f.fileno())
f = open('example', 'r')
printAddressBook(f.fileno())