Python protocbuf

创建pb协议文件

文件名:person.proto

syntax = "proto3";
import "google/protobuf/any.proto";
package example;

message person {   
    int32 id = 1;
    string name = 2;
}

message people{
    int32 id = 1;
    string name = 2;
    int32 sex = 3;
}

message all_person {    
	repeated person Per = 1;
}

message context_mgs{
    int32 type = 1;
    google.protobuf.Any obj =2;
}

protobuf 序列化与反序列化

# -*- coding: utf-8 -*-
from example import person_pb2
 
# 为 all_person 填充数据
pers = person_pb2.all_person()
p1 = pers.Per.add()
p1.id = 1
p1.name = 'zhangsan'
p2 = pers.Per.add()
p2.id = 2
p2.name = 'lisi'
 
# 对数据进行序列化
data = pers.SerializeToString()
 
# 对已经序列化的数据进行反序列化
target = person_pb2.all_person()
target.ParseFromString(data)
print(target.Per[1].name)  #  打印第一个 person name 的值进行反序列化验证

python循环遍历某个repeated字段

# for循环遍历
for per in target.Per:
	print(per)

获取某个repeated字段的size

# 使用python的len函数即可
print("length:",len(target.Per))

按序号取repeated字段的值

# 使用中括号"[]"
for i in range(0,len(target.Per)):
	print("per[",i,"]",target.Per[i])

any 字段操作

# 封包
context = person_pb2.context_mgs()
context.type = 1
context.obj.Pack(p1)

# 解包
if context.type == 1:
	per=person_pb2.person()
	if context.obj.Unpack(per):
		print(per)

你可能感兴趣的:(python常用操作,python,开发语言)