1.下載,配置環境變量
下載地址:https://github.com/google/protobuf/releases,選擇protoc-xxx-win64.zip下載
把.exe文件的位置加入到Path中
2.建立一個protoc文件test2.protoc
文件位置:最好跟環境變量不在一個盤,不知道什么原因,我環境變量在D盤,protoc文件也在D盤就不認識,放到F盤就可以。
test2.protoc內容:
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,回車,進入命令窗口
執行命令:
#第一個是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代碼,報錯:
因為測試,使用的是系統默認的臨時python環境,沒有安裝相關模塊,需要安裝一下 :
pip install protobuf pip install google
再執行:
python test.py
出現下面情況,表示成功:
參考:
https://www.cnblogs.com/luyanjie/p/10403869.html
https://blog.csdn.net/liupeifeng3514/article/details/78985575
https://stackoverflow.com/questions/38680593/importerror-no-module-named-google-protobuf