python使用protobuf

來源:互聯網
上載者:User

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 sysimport DataService_pb2#create protorow = DataService_pb2.RowProto()row.null_map = 1row.column.append("wang")row.column.append("female")row_str=row.SerializeToString()print row_strtable = DataService_pb2.TableProto()table.column.append("name")table.column.append("gender")table.row.append(row_str)table_str = table.SerializeToString()#process prototable_proto = DataService_pb2.TableProto()table_proto.ParseFromString(table_str)print "column:"print table_proto.columnrow_str = table_proto.row[0]row_proto = DataService_pb2.RowProto()row_proto.ParseFromString(row_str.encode('utf8'))print "row1:"print row_proto.column

讀檔案

import sysimport 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()


相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.