最近一段时间经常处理 protobuf
相关的内容,做一个demo
积累一下知识,关于protobuf
相关知识就不介绍了,网上有很多优秀的内容,在这主要给几个Python
demo
,介绍pb
与json
的相互转换与写的操作。
syntax = "proto2";
message TextInfo {
required string text1 = 1; // text1
optional string text2 = 2; // text2
repeated int32 text_cnt = 3; // text 个数
};
protoc -I=./ --python_out=. proto/*.proto
# 编译出 Python文件
# =============================================================
# !/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)
多学习,多积累,不要等到挨打的时候,才发现自己没有本事打回去,哈哈 愿与君共勉
声明: 总结学习,有问题或不当之处,可以批评指正哦,谢谢。