說明:
基於windows安裝protobuf,下載地址https://github.com/protocolbuffers/protobuf/releases
1.解壓到指定目錄,將bin目錄添加到環境變量,我的電腦->屬性->高級系統設置->環境變量->系統變量->Path,復制粘貼路徑;
2.bin文件中的protcobuf.exe拷貝到windows/system32目錄中,打開cmd,輸入protoc,查看安裝是否成功。
Protco的使用:
1.python安裝protco
python -m pip install upgrade
python -m pip install protobuf
使用
使用Protobuf有如下幾個步驟:
- 定義消息
- 初始化消息以及存儲傳輸消息
- 讀取消息並解析
1.定義消息
package my;
message helloworld
{
required int32 id = 1;
required string str = 2;
optional int32 wow = 3;
}
然后我們需要使用protoc進行編譯
protoc -I=./ --python_out=./ ./my.helloworld.proto
- -I: 是設定源路徑
- --python_out: 用於設定編譯后的輸出結果,如果使用其它語言請使用對應語言的option
- 最后一個參數是你要編譯的proto文件
消息初始化和存儲傳輸
我們來通過writer.py來初始化消息並存儲為文件,代碼如下:
from my.helloworld_pb2 import helloworld
def main():
hw = helloworld()
hw.id = 123
hw.str = "eric"
print hw
with open("mybuffer.io", "wb") as f:
f.write(hw.SerializeToString())
if __name__ == "__main__":
main()
執行writer.py之后就會將序列化的結果存儲在文件mybuffer.io中.
消息讀取與解析
我們通過reader.py來讀取和解析消息,代碼如下:
from my.helloworld_pb2 import helloworld
def main():
hw = helloworld()
with open("mybuffer.io", "rb") as f:
hw.ParseFromString(f.read())
print hw.id
print hw.str
if __name__ == "__main__":
main()
