protobuf是google开发的一种数据序列化方式,据说性能优于json,可以跨平台使用。分2和3两个版本,相互不兼容。
安装
下载对应版本:https://github.com/google/protobuf/releases
解压后,配置环境变量path,添加目录:D:\Program Files\protoc-3.17.1-win64\bin
cmd中可以运行protoc命令即为配置完毕
使用(python)
以proto3为例
- 编写proto文件(protobuf_example.proto):
syntax = "proto3";
message Example{
string name = 1;
int32 id = 2;
string notes = 3;
}
在当前文件目录下cmd运行下述命令编译
protoc --python_out=./ protobuf_example.proto
--python_out表示输出python文件,最后一个参数指定需要编译的文件名称,运行后,当前目录下会有文件:```protobuf_example_pb2.py```
序列化
创建python文件(protobuf_test.py)
from protobuf_example_pb2 import Example
import os
import sys
def main():
example = Example()
example.name = 'example1'
example.id = 1
example.notes = 'from python'
with open(sys.path[0] + '\\test_info.pb', 'wb') as f:
# sys.path[0]获取当前python文件所在目录
f.write(example.SerializeToString())
if __name__ == '__main__':
main()
运行后,当前目录下会生成序列化的文件test_info.pb
解析(反序列化)
from protobuf_example_pb2 import Example
import sys
def parse():
read_example = Example()
with open(sys.path[0] + '\\test_info.pb', 'rb') as f:
read_example.ParseFromString(f.read())
print(read_example)
print(read_example.name)
print(read_example.id)
print(read_example.notes)
if __name__ == '__main__':
parse()
输出示例如下:
name: "example"
id: 1
notes: "from python"