本文將從以下幾點來介紹protobuf:
1.安裝
2.定義protobuf消息格式
3.編譯protobuf
4.讀寫protobuf
1.安裝
2.定義protobuf消息格式
我們將要使用的示例是一個非常簡單的“地址簿”應用程序,可以在文件中讀取和寫入人員的聯系人詳細信息。地址簿中的每個人都有姓名,ID,電子郵件地址和聯系電話號碼。
要創建地址簿應用程序,需要從.proto文件開始。.proto文件中的定義很簡單:為要序列化的每個數據結構添加消息,然后為消息中的每個字段指定名稱和類型。下面是.proto定義的消息文件addressbook.proto。
syntax = "proto2";
package tutorial;
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phones = 4;
}
message AddressBook {
repeated Person people = 1;
}
關于protobuf的詳細解釋。
3.編譯protobuf
現在,有了一個.proto,需要做的下一件事就是生成需要讀寫的類AddressBook(包擴Person和PhoneNumber)消息。要做到這一點,需要運行protobuf編譯器protoc.exe對.proto進行編譯,編譯命令格式如下:
protoc -I = $ SRC_DIR --python_out = $ DST_DIR $ SRC_DIR / addressbook.proto
其中,$ SRC_DIR是源目錄(應用程序的源代碼所在的位置 - 如果不提??供值,則使用當前目錄),$ DST_DIR 是目標目錄(希望生成的代碼在哪里,通常和$SRC_DIR相同)。
我的示例程序如下圖,protoc.exe編譯器和.proto文件都在同一個目錄下,如果沒有為protoc.exe配置環境變量,則需要在命令行窗口中切換到包含protoc.exe的文件夾(也就是下圖的the_use_of_protobuf文件夾)下運行下面的命令:
protoc --python_out=./ ./addressbook.proto
然后生成
4.讀寫protobuf消息
-
寫一條消息
現在嘗試使用protobuf類。為了將個人詳細信息寫入地址簿文件,需要創建并填充protobuf類的實例,然后將它們寫入輸出流。
這是一個程序(文件名為write.py),它從數據文件中(這里的數據文件名為data.pb)讀取AddressBook類,根據用戶輸入添加一個新Person到AddressBook中,然后再將新AddressBook寫回文件。
#! /usr/bin/python
import addressbook_pb2
import sys
# This function fills in a Person message based on user input.
def PromptForAddress(person):
person.id = int(raw_input("Enter person ID number: "))
person.name = raw_input("Enter name: ")
email = raw_input("Enter email address (blank for none): ")
if email != "":
person.email = email
while True:
number = raw_input("Enter a phone number (or leave blank to finish): ")
if number == "":
break
phone_number = person.phones.add()
phone_number.number = number
type = raw_input("Is this a mobile, home, or work phone? ")
if type == "mobile":
phone_number.type = addressbook_pb2.Person.MOBILE
elif type == "home":
phone_number.type = addressbook_pb2.Person.HOME
elif type == "work":
phone_number.type = addressbook_pb2.Person.WORK
else:
print "Unknown phone type; leaving as default value."
# Main procedure: Reads the entire address book from a file,
# adds one person based on user input, then writes it back out to the same
# file.
if len(sys.argv) != 2:
print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
sys.exit(-1)
address_book = addressbook_pb2.AddressBook()
# Read the existing address book.
try:
f = open(sys.argv[1], "rb")
address_book.ParseFromString(f.read())
f.close()
except IOError:
print sys.argv[1] + ": Could not open file. Creating a new one."
# Add an address.
PromptForAddress(address_book.people.add())
# Write the new address book back to disk.
f = open(sys.argv[1], "wb")
f.write(address_book.SerializeToString())
f.close()
然后在命令窗口下執行以下命令:
python write.py data.pb
在彈出來的窗口隨便輸入兩條信息。
- 讀一條信息
#! /usr/bin/python
import addressbook_pb2
import sys
# Iterates though all people in the AddressBook and prints info about them.
def ListPeople(address_book):
for person in address_book.people:
print "Person ID:", person.id
print " Name:", person.name
if person.HasField('email'):
print " E-mail address:", person.email
for phone_number in person.phones:
if phone_number.type == addressbook_pb2.Person.MOBILE:
print " Mobile phone #: ",
elif phone_number.type == addressbook_pb2.Person.HOME:
print " Home phone #: ",
elif phone_number.type == addressbook_pb2.Person.WORK:
print " Work phone #: ",
print phone_number.number
# Main procedure: Reads the entire address book from a file and prints all
# the information inside.
if len(sys.argv) != 2:
print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
sys.exit(-1)
address_book = addressbook_pb2.AddressBook()
# Read the existing address book.
f = open(sys.argv[1], "rb")
address_book.ParseFromString(f.read())
f.close()
ListPeople(address_book)
然后在命令窗口下執行以下命令:
python read.py data.pb
你可以看到輸出
到此,關于protobuf的簡單使用已經介紹完了。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
