protobuf编译工具使用

 

1.下载,配置环境变量

下载地址:https://github.com/google/protobuf/releases,选择protoc-xxx-win64.zip下载html

 

把.exe文件的位置加入到Path中java

 

2.创建一个protoc文件test2.protoc

文件位置:最好跟环境变量不在一个盘,不知道什么缘由,我环境变量在D盘,protoc文件也在D盘就不认识,放到F盘就能够。python

test2.protoc内容:git

syntax = "proto2"; message testinfo { required int32 devtype = 1; required int32 devid = 2; required int32 unitid = 3; required int32 chlid = 4; optional int32 testid = 5 [default = 0]; required bytes stepdata = 6; }

 

在文件路径输入cmd,回车,进入命令窗口github

 

 

 执行命令:测试

#第一个是protoc文件的路径,第二个是编译文件的路径 #protoc -I=源地址 --java_out=目标地址 xxx.proto protoc -I=F:\protocbuf_test --java_out=F:\protocbuf_test test2.proto

#此处生成python文件 protoc
--python_out=./ test2.proto


#默认生成.java文件
protoc -I=F:\protocbuf_test --java_out=F:\protocbuf_test test2.proto

 

 

 

 3.在目录下新建文件 test.py,写入代码

import test2_pb2 testinfo = test2_pb2.testinfo() testinfo.devtype = 100 testinfo.devid = 2 testinfo.unitid = 3 testinfo.chlid = 4 testinfo.testid = 250 testinfo.stepdata = b'abd'

print(testinfo, testinfo.devtype)  # 打印 protobuf 结构的内容
out = testinfo.SerializeToString() print(out)  # 打印 Protobuf 序列字符串
 decode = test2_pb2.testinfo() decode.ParseFromString(out) print(decode) # 打印 解析Protobuf后的内容

 

运行python代码,报错:ui

 

 

 

由于测试,使用的是系统默认的临时python环境,没有安装相关模块,须要安装一下 :google

pip install protobuf pip install google

再执行:spa

python test.py

出现下面状况,表示成功:.net

 

 

 

 

 

参考:

http://www.javashuo.com/article/p-ysvkcejq-cx.html

http://www.javashuo.com/article/p-piaiuagd-es.html

https://stackoverflow.com/questions/38680593/importerror-no-module-named-google-protobuf

相关文章
相关标签/搜索