搭建环境

python 2.7.9
win10
protobuf 3.5.0
pycharm

protobuf编译工具protoc安装

下载 protoc-3.5.0-win32.zip.

解压缩到指定目录,配置环境变量PATH。

打开命令行窗口输入:protoc –version 测试。

protobuf python安装

1
pip install protobuf

测试:

1
2
python
>> import google.protobuf

demo测试

  1. 创建test.proto描述文件
1
2
3
4
5
message CDevice
{
optional int32 devId = 1;
optional string name = 2;
}
  1. 使用protoc编译test.proto为test_pb2.py文件
1
protoc -I ./origin --python_out=./test ./origin/test.proto
  1. 编写测试python测试编译生成的py
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
# -*- coding: UTF-8 -*-
import test_pb2
import traceback
import sys


try:
sendData = test_pb2.CDevice()
sendData.devId = 9
sendData.name = 'USB'

#Serialize
sendDataStr = sendData.SerializeToString()
#print serialized string value
print 'serialized string:', sendDataStr
#------------------------#
# message transmission #
#------------------------#
receiveDataStr = sendDataStr
receiveData = test_pb2.CDevice()

#Deserialize
receiveData.ParseFromString(receiveDataStr)
print 'pares serialize string, return: devId = ', receiveData.devId, ', name = ', receiveData.name
except Exception, e:
print Exception, ':', e
print traceback.print_exc()
errInfo = sys.exc_info()
print errInfo[0], ':', errInfo[1]