mirror of
https://github.com/capnproto/pycapnp.git
synced 2025-03-05 17:01:01 +01:00
54 lines
1.3 KiB
Python
54 lines
1.3 KiB
Python
from __future__ import print_function
|
|
import os
|
|
import capnp
|
|
|
|
this_dir = os.path.dirname(__file__)
|
|
addressbook = capnp.load(os.path.join(this_dir, 'addressbook.capnp'))
|
|
|
|
print = lambda *x: x
|
|
|
|
|
|
def writeAddressBook(f):
|
|
addressBook = addressbook.AddressBook.new_message()
|
|
people = addressBook.init('people', 2)
|
|
|
|
alice = people[0]
|
|
alice.id = 123
|
|
alice.name = 'Alice'
|
|
alice.email = 'alice@example.com'
|
|
alicePhones = alice.init('phones', 1)
|
|
alicePhones[0].number = "555-1212"
|
|
alicePhones[0].type = 'mobile'
|
|
|
|
bob = people[1]
|
|
bob.id = 456
|
|
bob.name = 'Bob'
|
|
bob.email = 'bob@example.com'
|
|
bobPhones = bob.init('phones', 2)
|
|
bobPhones[0].number = "555-4567"
|
|
bobPhones[0].type = 'home'
|
|
bobPhones[1].number = "555-7654"
|
|
bobPhones[1].type = 'work'
|
|
|
|
addressBook.write(f)
|
|
|
|
|
|
def printAddressBook(f):
|
|
addressBook = addressbook.AddressBook.read(f)
|
|
|
|
for person in addressBook.people:
|
|
print(person.name, ':', person.email)
|
|
for phone in person.phones:
|
|
print(phone.type, ':', phone.number)
|
|
print()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
for i in range(10000):
|
|
f = open('example', 'w')
|
|
writeAddressBook(f)
|
|
|
|
f = open('example', 'r')
|
|
printAddressBook(f)
|
|
|
|
os.remove('example')
|