Google Protocol Buffer

相关文章:

Google Protocol Buffer 的使用和原理

Protocol Buffer技术详解 --C++

如何使用GPB   --C++

如何在python中使用protocol buffer     --Python

 

Python实例

testpb.proto

message people
{
optional string name = 1;
optional int32 height = 2;
}

 

test_protocbuf.py

#coding=utf8
import sys
import testpb_pb2   
#testpb_pb2.py文件由protoc命令通过proto数据文件生成

def Body_serialize(name, height):
    testpp = testpb_pb2.people()
    testpp.name = name
    testpp.height = height
    
    #序列化的
    sname = testpp.SerializeToString()
    print len(sname)
    return sname

def Body_unserialize(sname):
    testpp = testpb_pb2.people()
    
    #反序列化
    testpp.ParseFromString(sname)
    return testpp

    
yn_Body_serialize = ["0", "1"]  #序列化or反序列化
#参数检查
arglen = len(sys.argv)
if 2 > arglen:
    print "Uage: number of args is error!"
    sys.exit()
    
if yn_Body_serialize[0] == sys.argv[1]:
    if 4 != arglen:
        print "Uage: number of args is error!"
        sys.exit()
    name = sys.argv[2]
    height = int(sys.argv[3])
    body_serialize = Body_serialize(name, height)
    
    #写入文件
    f = open("D:\\CODE\\Python\\test_protocbuf\\buftmp","wb")
    f.write(body_serialize)
    f.close()
    print body_serialize
    
elif yn_Body_serialize[1] == sys.argv[1]:
    if 2 != arglen:
        print "Uage: number of args is error!"
        sys.exit()
    
    #读文件中的序列化数据
    f = open("D:\\CODE\\Python\\test_protocbuf\\buftmp","rb")
    body_serialize = f.read()
    f.close()
    #body_serialize = sys.argv[2]
    
    body = Body_unserialize(body_serialize)
    print body
    
else:
    print sys.argv[1]
    print "Uage: argv[1] is error!"
    sys.exit()
 

 

你可能感兴趣的:(Google Protocol Buffer)