python读写protobuf

时间:2023-03-10 02:11:18
python读写protobuf
0.     前期准备
官方protobuf定义

https://code.google.com/p/protobuf/

python使用指南
https://developers.google.com/protocol-buffers/docs/pythontutorial
http://blog.****.net/love_newzai/article/details/6906459
安装 python对protobuf的支持
wget https://protobuf.googlecode.com/files/protobuf-2.5.0.tar.bz2
tar -vxjf protobuf-2.5.0.tar.bz2
cd protobuf-2.5.0
./configure --prefix=/home/admin/mypython/
make ; make install
1     准备.proto文件
struct_oss_pb.proto
 message entity_attr
{
required int32 attr_id = 1; // 属性类型标识,比如:标题属性为 1,正文属性为2,图片属性为 3,发现时间属性为4,原始url属性为5 ,父页面属性为 6;
required bytes attribute = 2; // 属性类型描述,比如“标题”,“ 正文”,“图片”,“发现时间”,“原始 url”,“父页面 ”等
repeated bytes value = 3; // 属性值,除“图片”只保留 osskey之外,其他保留原文。考虑到文章中会保留多幅图,所以采用repeated。
}; message entity_desc
{
required int32 entity_id = 1; // 实体类型标识,比如:新闻为 1,小说为2 。
required bytes entity_name = 2; // 实体名称,比如:新闻主题事件关键词,小说名等。
repeated entity_attr attributes = 3; // 属性描述,格式见entity_attr。
};
2.     将proto转化为 xxx_pb2.py ,然后在你的程序里import这个py
protoc --python_out=./ ./struct_oss_pb.proto
得到struct_oss_pb_pb2.py
3.     读写protobuf的示例python
test_pb.py
01 # coding: gbk
02 import struct_oss_pb_pb2
03 entitydesc=struct_oss_pb_pb2.entity_desc()
04 entitydesc.entity_id=1
05 entitydesc.entity_name='haha'
06
07 #create proto
08 entityattr=entitydesc.attributes.add() #嵌套message
09 entityattr.attr_id = 11
10 entityattr.attribute = '标题'.decode('gbk').encode('utf-8')
11 entityattr.value.append("title adfadf")
12
13 entity_attr_str=entityattr.SerializeToString()
14 print entity_attr_str
15 entitydesc_str=entitydesc.SerializeToString()
16 print entitydesc_str
17 print '----'
18 #read
19 entityattr2 = struct_oss_pb_pb2.entity_attr()
20 entityattr2.ParseFromString(entity_attr_str)
21 print entityattr2.attr_id
22 print entityattr2.attribute.decode('utf-8').encode('gbk')
23 for i in entityattr2.value:
24 print i
25
26 print '----'
27 entitydesc2=struct_oss_pb_pb2.entity_desc()
28 entitydesc2.ParseFromString(entitydesc_str)
29 print entitydesc2.entity_id
30 #repeated entity_attr attributes,由于是repeated需要遍历
31 for oneatt in entitydesc2.attributes:
32 print oneatt.attr_id
33 for i in oneatt.value:
34 print i

Protobuf定义了一套基本数据类型。几乎都可以映射到C++\Java等语言的基础数据类型.

protobuf 数据类型

描述

打包

C++语言映射

bool

布尔类型

1字节

bool

double

64位浮点数

N

double

float

32为浮点数

N

float

int32

32位整数、

N

int

uint32

无符号32位整数

N

unsigned int

int64

64位整数

N

__int64

uint64

64为无符号整

N

unsigned __int64

sint32

32位整数,处理负数效率更高

N

int32

sing64

64位整数 处理负数效率更高

N

__int64

fixed32

32位无符号整数

4

unsigned int32

fixed64

64位无符号整数

8

unsigned __int64

sfixed32

32位整数、能以更高的效率处理负数

4

unsigned int32

sfixed64

64为整数

8

unsigned __int64

string

只能处理 ASCII字符

N

std::string

bytes

用于处理多字节的语言字符、如中文

N

std::string

enum

可以包含一个用户自定义的枚举类型uint32

N(uint32)

enum

message

可以包含一个用户自定义的消息类型

N

object of class