python简单使用protobuf,以及一个demo例子

python使用protobuf

1、下载protoc, 在网页的最下面,下载protoc-3.12.4-win64.zip解压即可
githubProtocol Buffers v3.12.4

2、写.proto文件
写法参见Language Guide (proto3)

3、编译

protoc,意思是用protoc编译,
--python_out=./ 意思是编译好的文件输出到当前目录,当然想写到哪写到哪,
your_message.proto, 意思是你的源文件(当前目录下的)
protoc --python_out=./ your_message.proto

4、将编译好的文件放到python文件夹中即可使用

如下例子
.test.proto

syntax = "proto3";
message TestMsg {
    string name = 1;
}

test_pb2.py

不看了,自动编译成的

test.py

from test_pb2 import TestMsg

send_msg = TestMsg()
send_msg.name = '你妈必死'

send_bytes = send_msg.SerializeToString()
recv_msg = TestMsg()
recv_msg.ParseFromString(send_bytes)
print recv_msg.name

执行结果

你妈必死

是不是很简单?

猜你喜欢

转载自blog.csdn.net/qq_40666620/article/details/108076841