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_py
00000000 08 65 12 05 68 65 6c 6c 6f |.e..hello|
00000009
$
'''
import helloworld_pb2
msg = helloworld_pb2.helloworld()
msg.id = 101
msg.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
101
hello
DONE.
$
'''
import helloworld_pb2
msg = helloworld_pb2.helloworld()
f = open("./log_py", "rb")
msg.ParseFromString(f.read())
f.close()
print msg.id
print msg.str
print "DONE."