1.安装protobuf编译器
./configure --prefix=dist; make; make install; 配置bin路径
2.进入解压后的python目录下
参考README.txt,python setup.py install
3.使用
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()