下面都是在windows上完成的:
1、安装protobuf:
1)使用pip安装:
pip install protobuf>=2.5.0 2)源码安装:
下载,然后python setup.py install
2、使用:
pb文件:
message RowProto {  
required uint32 null_map = 1;  
repeated string column = 2;  
}  
  
message TableProto {  
repeated string column = 1;  
repeated string row = 2;  
} 编译:
protoc --python_out=/data/home/ ./DataService.proto得到DataService_pb2.py
解析:
import sys  
import DataService_pb2  
  
#create proto  
row = DataService_pb2.RowProto()  
row.null_map = 1  
row.column.append("wang")  
row.column.append("female")  
row_str=row.SerializeToString()  
print row_str  
table = DataService_pb2.TableProto()  
table.column.append("name")  
table.column.append("gender")  
table.row.append(row_str)  
table_str = table.SerializeToString()  
  
#process proto  
table_proto = DataService_pb2.TableProto()  
table_proto.ParseFromString(table_str)  
print "column:"  
print table_proto.column  
  
row_str = table_proto.row[0]  
row_proto = DataService_pb2.RowProto()  
row_proto.ParseFromString(row_str.encode('utf8'))  
print "row1:"  
print row_proto.column 读文件:
import sys  
import DataService_pb2  
  f = open("table", 'rb',)  
  table_proto = DataService_pb2.TableProto()  
  table_proto.ParseFromString(f.read())  
  print table_proto.column  
  #print table_proto.row  
  for row in table_proto.row:  
    row_proto = DataService_pb2.RowProto()  
    row_proto.ParseFromString(row.encode('utf-8'))  
    print row_proto.column  
  f.close()                









