Python protobuf 的基本处理

Python protobuf 的基本处理

最近一段时间经常处理 protobuf 相关的内容,做一个demo积累一下知识,关于protobuf 相关知识就不介绍了,网上有很多优秀的内容,在这主要给几个Python demo,介绍pbjson 的相互转换与写的操作。

1、protobuf 的编译

1.1 protobuf demo

syntax = "proto2";
message TextInfo {
    required string text1 = 1;  // text1
    optional string text2 = 2;  // text2
    repeated int32 text_cnt = 3; // text 个数
};

1.2 编译命令

~/opt/anaconda3/bin/protoc -I=./  --python_out=. proto/*.proto

# 如果报anaconda3 没有 protoc 命令 安装一下
# conda install -c anaconda protobuf
# 编译出 Python文件

在这里插入图片描述

2、Python 读写操作

2.1 demo.py

# =============================================================
# !/usr/bin/python
# -*- coding=utf-8 -*-
# Name:         demo
# Description:
# Author:       liu
# Date:         2021/3/4
# Mail:         
# =============================================================

from __future__ import absolute_import
from __future__ import print_function
from __future__ import division

import sys
sys.path.append('./proto')

from demo_pb2 import TextInfo
from google.protobuf.json_format import MessageToJson
from google.protobuf.json_format import MessageToDict


text_info = TextInfo()
text_info.text1 = 'hello beijing'
text_info.text2 = 'hello shanghai'
text_info.text_sum.append('hello beijing')
text_info.text_sum.append('hello shanghai')

print('text_info type is %s' % type(text_info))
print(text_info)

text_info_json = MessageToJson(text_info)  # 把pb 转换成字符串 json
print('text_info_json type is %s' % type(text_info_json))
print(text_info_json)

text_info_dict = MessageToDict(text_info)  # 把pb 转换成dict
print('text_info_dict type is %s' % type(text_info_dict))
print(text_info_dict)

2.2 输出结果

在这里插入图片描述

3、总结

多学习,多积累,不要等到挨打的时候,才发现自己没有本事打回去,哈哈 愿与君共勉

声明: 总结学习,有问题或不当之处,可以批评指正哦,谢谢。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值