protobuf

来源:互联网 发布:淘宝服装推广方案 编辑:程序博客网 时间:2024/05/22 00:30

Overview

这一节给出Python代码使用protobuf的例子。

proto file

使用之前的示例消息结构。

/*protoc -I=. --cpp_out=. helloworld.proto protoc -I=. --python_out=. helloworld.proto */message helloworld {     required int32     id = 1;  // ID     required string    str = 2;  // str     optional int32     opt = 3;  //optional field }

compile proto file

protoc -I=. --python_out=. helloworld.proto

Writer

#!/usr/bin/python'''$ chmod +x writer.py$ ./writer.py DONE.$ hexdump -C log_py00000000  08 65 12 05 68 65 6c 6c  6f        |.e..hello|00000009$ '''import helloworld_pb2msg = helloworld_pb2.helloworld()msg.id = 101msg.str = "hello"f = open("./log_py", "wb")f.write(msg.SerializeToString())f.close()print "DONE."

Reader

#!/usr/bin/python'''$ chmod +x reader.py $ ./reader.py 101helloDONE.$'''import helloworld_pb2msg = helloworld_pb2.helloworld()  f = open("./log_py", "rb")msg.ParseFromString(f.read())f.close()print msg.idprint msg.strprint "DONE."