protobuf

前々から気になっていたプロトコルバッファを試してみた。
http://code.google.com/p/protobuf/からprotoc-2.2.0-win32.zipをダウンロードしてPATHの通ったところへ配置。
定義ファイル hoge.proto

message Person {
  required int32 id = 1;
  required string name = 2;
  optional string email = 3 [default = "なし"];
}
message Group {
  repeated Person persons = 1;
}

コンパイル

$ protoc --python_out= hoge.proto

サンプルコード hoge_test.py

from hoge_pb2 import *
import zlib
BINARY = 'hoge.bin'

# 読み込みテスト
def read():
  print 'read!!'
  g = Group()
  with open(BINARY, 'rb') as f:
    g.ParseFromString(zlib.decompress(f.read()))
  for p in g.persons:
    print ', '.join(map(unicode, (p.id, p.name, p.email)))

# 書き込みテスト
def write():
  print 'write!!'
  g = Group()
  
  p = g.persons.add()
  p.id = 0
  p.name = 'guido'
  p.email = 'guido@gmail.com'
  
  p = g.persons.add()
  p.id = 1
  p.name = 'larry'
  p.email = 'larry@gmail.com'
  
  p = g.persons.add()
  p.id = 2
  p.name = 'stroustrup'
  #p.email = 'stroustrup@gmail.com'
  
  with open(BINARY, 'wb') as f:
    f.write(zlib.compress(g.SerializeToString()))

write()
read()

実行結果。

$ python hoge_test.py
write!!
read!!
0, guido, guido@gamil.com
1, larry, larry@gamil.com
2, stroustrup, なし

お手軽です。