摘要
项目中引入proto的依赖
【两种方法】:
方法1、 官网下载对应的语言包 ,这里下载protobuf-python-3.5.1.tar.gz ,解压后进入python-protobuf-3.5.1/python
目录,执行python3 setup.py install
方法2 、【推荐】命令行执行pip3 install protobuf
,此时会下载最新的protobuf版本,如果下载的版本与本地安装的proto命令版本不一致,有可能导致异常,所以此时最好指定要下载的版本号:pip3 install protobuf==3.5.1
【注意】
上面的安装方式是全局安装,安装成功后对应的依赖包都会被安装到对应的site-packages目录下,比如/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages
使用IDE开发时,如PyCharm,绑定interpreter时要注意勾选inherit global site-packages
,这样项目才能使用全局依赖中的所有包
如果只是为当前项目安装依赖包可以不勾选inherit global site-packages
,然后进入当前项目依赖的pip目录,即Location
指定的路径下,执行./bin/pip install protobuf==3.5.1
来安装需要的依赖包
准备proto文件
proto示例文件参考[Protocol Buffer学习笔记(Java&NodeJS)]
(https://www.jianshu.com/p/55f4b4b22dd2 )
python同时支持proto2和proto3,所以如果基于proto3,这里注意去掉其中的required
、optional
,因为这里要求语法严格遵循proto3,不能在属性前出现required
、optional
,同时文件顶端要明确syntax = "proto3";
生成proto对应的python文件
python中使用protobuf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 from proto import OTIpcDef_pb2otIpcList = OTIpcDef_pb2.OTIpcList() otIpc = otIpcList.otpic.add() otIpc.CompanyId = "companyId" otIpc.Source = "Source" otIpc.IPCType = OTIpcDef_pb2.baseInfoCompany baseInfoCompany = otIpc.baseInfoCompany.add() baseInfoCompany.Address = 110011 baseInfoCompany.CompanyId = "companyId" baseInfoCompany.CompanyName = "companyName中文" baseInfoCompany.Identifier = "identifier" baseInfoCompany.BusinessScope = "BusinessScope" baseInfoCompany.ContactAddress = "ContactAddress" baseInfoCompany.EconomicType = "EconomicType" baseInfoCompany.RegCapital = "RegCapital" baseInfoCompany.LegalName = "LegalName" baseInfoCompany.LegalID = "LegalID" baseInfoCompany.LegalPhone = "LegalPhone" baseInfoCompany.State = 0 baseInfoCompany.Flag = 1 baseInfoCompany.UpdateTime = 20180226121212 otIpc2 = otIpcList.otpic.add() otIpc2.CompanyId = "companyId" otIpc2.Source = "Source" otIpc2.IPCType = OTIpcDef_pb2.baseInfoCompanyStat baseInfoCompanyStat = otIpc2.baseInfoCompanyStat.add() baseInfoCompanyStat.CompanyId = "companyId" baseInfoCompanyStat.DriverNum = 10 baseInfoCompanyStat.Flag = 0 baseInfoCompanyStat.UpdateTime = 20180226121212 baseInfoCompanyStat.VehicleNum = 5 print ("============================================" )print (otIpcList)print ("============================================" )b = otIpcList.SerializeToString() print (b)print ("============================================" )otIpcList2 = OTIpcDef_pb2.OTIpcList() otIpcList2.ParseFromString(b) print (otIpcList2)