Protobuf是Google开发的序列化结构数据的一套工具,适合用于数据存储,以及不同语言不同应用之间进行通信的数据交换格式。目前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,是每个值唯一对应的tag* 1-15因为使用少于1 byte,通常用来表示repeated的值* >16的数用来表示其他值*/ 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; } /** 每个值都需要一个标记,有三种类型的标记* required: 必须赋值,否则会出现未初始化的错误* optional: 可以赋值,可以为空,赋默认值* repeated: 赋任意个数的值*/ 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# 根据提示,用户输入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化之后的二进制string值。with open(sys.argv[1], "wb") as f: f.write(address_book.SerializeToString())

调用该python文件, 进行符合protobuf格式的数据输入,例如

$ 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化后的二进制文件,类似

test{test@google.com"

0001112222"

1110003333

Protobuf的使用:读信息

读信息,也叫做解析PB化的数据。

#! /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)

输出结果类似于

Person ID: 123

Name: test

E-mail address: test@google.com

Work phone #: 0001112222

Work phone #: 1110003333

Message常用的方法:IsInitialized(): 检查所有required的值是否已经赋值

_str_(): 用于debug,返回人类可读的数据

CopyFrom(other_msg): 根据已知message对新message赋值

Clear(): 将所有元素清空

SerializedToString(): 将message数据进行序列化,返回PB化之后的二进制string

ParseFromString(): 将二进制string,解析PB数据,返回message数据

pythongoogle.probuf.timestamp_数据通信格式:Google Protobuf相关推荐

  1. pythongoogle.probuf.timestamp_gRPC快速入门(一)——Protobuf简介

    gRPC快速入门(一)--Protobuf简介 一.Protobuf简介 1.Protobuf简介 Protobuf即Protocol Buffers,是Google公司开发的一种跨语言和平台的序列化 ...

  2. google ProtoBuf开发者指南

    目录 1   概览 1.1   什么是protocol buffer 1.2   他们如何工作 1.3   为什么不用XML? 1.4   听起来像是为我的解决方案,如何开始? 1.5   一点历史 ...

  3. 使用CSharp编写Google Protobuf插件

    什么是 Google Protocol Buffer? Google Protocol Buffer( 简称 Protobuf) 是 Google 公司内部的混合语言数据标准,目前已经正在使用的有超过 ...

  4. Google protobuf使用技巧和经验

    Google protobuf是非常出色的开源工具,在项目中可以用它来作为服务间数据交互的接口,例如rpc服务.数据文件传输等.protobuf为proto文件中定义的对象提供了标准的序列化和反序列化 ...

  5. google protobuf安装与使用

    google protobuf是一个灵活的.高效的用于序列化数据的协议.相比较XML和JSON格式,protobuf更小.更快.更便捷.google protobuf是跨语言的,并且自带了一个编译器( ...

  6. Google Protobuf 使用介绍

    直接在 www.google.com.hk 上搜索google protobuf 后下载官方版本. 官方版本支持C++\Java\Python三门语言. 还有很多非官方的语言版本支持,如C\NET(C ...

  7. Google Protobuf 开发指南

    为什么80%的码农都做不了架构师?>>>    Google Protobuf开发指南 1.简介 l  它是开源项目:http://code.google.com/p/protobu ...

  8. 《Dotnet9》系列-Google ProtoBuf在C#中的简单应用

    简介 什么是 Google Protocol Buffer? 假如您在网上搜索,应该会得到类似这样的文字介绍: Google Protocol Buffer( 简称 Protobuf) 是 Googl ...

  9. google protobuf使用

    google protobuf使用 下载的是github上的:https://github.com/google/protobuf If you get the source from github, ...

最新文章

  1. php引用php,PHP7引入的??和?:的区别讲解
  2. Linux的profile与bashrc的分析
  3. Thirft框架介绍
  4. Mac OS使用技巧十八:Safari碉堡功能之一制作Widget
  5. 计算机程序设计vb课后题,《VB程序设计》课后题答案
  6. C#中LINQ与数据管道
  7. 《C++高级编程(第3版)》
  8. 一分钟区分一流公司、二流公司、三流公司(转)
  9. JAVA面向对象初步知识总结:封装、继承、多态
  10. Linux系统编程 -- 进程控制 进程终止
  11. 自食其力!ASP.NET 4打造HTML5视频控件
  12. 全行业产业链图示(摘自企查查)
  13. 技术评审之技术文档的规范模板
  14. 大数据高冷?10个有趣的大数据经典案例
  15. “元宇宙”是什么?涂子沛:人可在数据空间“复活”
  16. 阿里云 (ECS 部署Javaweb 以及虚拟机操作)
  17. 2023养老展/山东养老服务业展/济南老年用品展/老龄产业展
  18. 关于Windows10 VT虚拟化无法开启
  19. error: C:\projects\opencv-python\opencv\modules\imgproc\src\imgwarp.cpp:5594: error: (-215) (M0.type
  20. Dynamics 365(on-premises)公告栏报错

热门文章

  1. HTML 5 样式指南和代码约定
  2. Spring基础知识汇总 Java开发必看
  3. MySQL查看表结构的实际操作命令简介
  4. Hadoop Distributed File System 简介
  5. 跟vczh看实例学编译原理——三:Tinymoe与无歧义语法分析
  6. 【OpenCV3】双线性插值
  7. SpringMVC学习系列(11) 之 表单标签
  8. Eos离线密钥生成的PHP代码
  9. 自己做站点(二) 20块钱搞定一个企业站:域名amp;空间申请
  10. android smack源码分析——接收消息以及如何解析消息