1. Download, configure the environment variables
Download: https://github.com/google/protobuf/releases , select protoc-xxx-win64.zip download
The location of the .exe file is added to the Path
2. The establishment of a protoc file test2.protoc
File location: with the best environment variable is not a dish, do not know why, I environment variable in the D drive, protoc document also does not know the D drive, you can put the F drive.
test2.protoc content:
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;
}
In the file path input cmd, enter into the command window
Excuting an order:
# The first is the path protoc file, and the second is the path of the compiled file
#protoc the -I = source address --java_out = destination address xxx.proto
protoc the -I = F: \ protocbuf_test --java_out = F: \ protocbuf_test test2.proto
generated python file # here
Protoc --python_out = / test2.proto.
# default generate .java file
Protoc - the I = F: \ protocbuf_test --java_out = F: \ protocbuf_test test2.proto
3. test.py new file in the directory, write the code
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