下載地址:https://github.com/google/protobuf/releases,選擇protoc-xxx-win64.zip下載html
把.exe文件的位置加入到Path中java
文件位置:最好跟環境變量不在一個盤,不知道什麼緣由,我環境變量在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
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