pythongoogle.probuf.timestamp_数据通信格式:Google Protobuf
Protobuf是Google開發(fā)的序列化結(jié)構(gòu)數(shù)據(jù)的一套工具,適合用于數(shù)據(jù)存儲,以及不同語言不同應(yīng)用之間進(jìn)行通信的數(shù)據(jù)交換格式。目前Google提供了C++,Python,Java,Go等語言的支持。
Protobuf的安裝
在Protobuf的github主頁上,google/protobuf,可以找到不同語言的安裝方法。
定義Protobuf格式
syntax = "proto3";// package 在python中沒用,但是在其他語言的工程中可以避免命名沖突package tutorial;import "google/protobuf/timestamp.proto";// [START messages]// message 是包含多個值的集合,支持bool,int32,float,double,string等message Person { /** =1,=2,是每個值唯一對應(yīng)的tag* 1-15因?yàn)槭褂蒙儆? byte,通常用來表示repeated的值* >16的數(shù)用來表示其他值*/ string name = 1; int32 id = 2; // Unique ID number for this person. string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { string number = 1; PhoneType type = 2; } /** 每個值都需要一個標(biāo)記,有三種類型的標(biāo)記* required: 必須賦值,否則會出現(xiàn)未初始化的錯誤* optional: 可以賦值,可以為空,賦默認(rèn)值* repeated: 賦任意個數(shù)的值*/ repeated PhoneNumber phones = 4; google.protobuf.Timestamp last_updated = 5;}// Our address book file is just one of these.message AddressBook { repeated Person people = 1;}// [END messages]
定義好protobuf的格式之后,就需要編譯,得到讀寫該protobuf的類文件。
protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/addressbook.proto
編譯之后將會生成 addressbook_pb2.py。
Protobuf的使用:寫信息
#! /usr/bin/env python# 根據(jù)提示,用戶輸入address信息,然后寫入AddressBook中。import addressbook_pb2import systry: raw_input # Python 2except NameError: raw_input = input # Python 3# 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: with open(sys.argv[1], "rb") as f: address_book.ParseFromString(f.read())except IOError: print(sys.argv[1] + ": File not found. Creating a new file.")# Add an address.PromptForAddress(address_book.people.add())# Write the new address book back to disk.# SerializeToString 用來序列化message,并返回PB化之后的二進(jìn)制string值。with open(sys.argv[1], "wb") as f: f.write(address_book.SerializeToString())
調(diào)用該python文件, 進(jìn)行符合protobuf格式的數(shù)據(jù)輸入,例如
$ python add_person.py address_book_test
Enter person ID number: 123
Enter name: test
Enter email address (blank for none): test@google.com
Enter a phone number (or leave blank to finish): 0001112222
Is this a mobile, home, or work phone? work
Enter a phone number (or leave blank to finish): 1110003333
Is this a mobile, home, or work phone? work
Enter a phone number (or leave blank to finish):
然后將會生成一個 address_book_test 的PB化后的二進(jìn)制文件,類似
test{test@google.com"
0001112222"
1110003333
Protobuf的使用:讀信息
讀信息,也叫做解析PB化的數(shù)據(jù)。
#! /usr/bin/env pythonfrom __future__ import print_functionimport addressbook_pb2import 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.email != "": print(" E-mail address:", person.email) for phone_number in person.phones: if phone_number.type == addressbook_pb2.Person.MOBILE: print(" Mobile phone #:", end=" ") elif phone_number.type == addressbook_pb2.Person.HOME: print(" Home phone #:", end=" ") elif phone_number.type == addressbook_pb2.Person.WORK: print(" Work phone #:", end=" ") 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.with open(sys.argv[1], "rb") as f: address_book.ParseFromString(f.read())ListPeople(address_book)
輸出結(jié)果類似于
Person ID: 123
Name: test
E-mail address: test@google.com
Work phone #: 0001112222
Work phone #: 1110003333
Message常用的方法:IsInitialized(): 檢查所有required的值是否已經(jīng)賦值
_str_(): 用于debug,返回人類可讀的數(shù)據(jù)
CopyFrom(other_msg): 根據(jù)已知message對新message賦值
Clear(): 將所有元素清空
SerializedToString(): 將message數(shù)據(jù)進(jìn)行序列化,返回PB化之后的二進(jìn)制string
ParseFromString(): 將二進(jìn)制string,解析PB數(shù)據(jù),返回message數(shù)據(jù)
總結(jié)
以上是生活随笔為你收集整理的pythongoogle.probuf.timestamp_数据通信格式:Google Protobuf的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python中接口测试垃圾数据如何清理_
- 下一篇: strlen函数_7.2 C++字符串处