说明:
基于windows安装protobuf,下载地址https://github.com/protocolbuffers/protobuf/releases
1.解压到指定目录,将bin目录添加到环境变量,我的电脑->属性->高级系统设置->环境变量->系统变量->Path,复制粘贴路径;
2.bin文件中的protcobuf.exe拷贝到windows/system32目录中,打开cmd,输入protoc,查看安装是否成功。
Protco的使用:
1.python安装protco
python -m pip install upgrade
python -m pip install protobuf
使用
使用Protobuf有如下几个步骤:
- 定义消息
- 初始化消息以及存储传输消息
- 读取消息并解析
1.定义消息
package my; message helloworld { required int32 id = 1; required string str = 2; optional int32 wow = 3; }
然后我们需要使用protoc进行编译
protoc -I=./ --python_out=./ ./my.helloworld.proto
- -I: 是设定源路径
- --python_out: 用于设定编译后的输出结果,如果使用其它语言请使用对应语言的option
- 最后一个参数是你要编译的proto文件
消息初始化和存储传输
我们来通过writer.py来初始化消息并存储为文件,代码如下:
from my.helloworld_pb2 import helloworld def main(): hw = helloworld() hw.id = 123 hw.str = "eric" print hw with open("mybuffer.io", "wb") as f: f.write(hw.SerializeToString()) if __name__ == "__main__": main()
执行writer.py之后就会将序列化的结果存储在文件mybuffer.io中.
消息读取与解析
我们通过reader.py来读取和解析消息,代码如下:
from my.helloworld_pb2 import helloworld def main(): hw = helloworld() with open("mybuffer.io", "rb") as f: hw.ParseFromString(f.read()) print hw.id print hw.str if __name__ == "__main__": main()