Protobuf(Protocol Buffers)超详细入门教程(跨平台序列化, Python)——更新于2022.01

相关教程

相关文献

protocol buffers是谷歌的语言中立、平台中立、可扩展的结构化数据序列化机制——XML,但更小、更快、更简单。您可以一次定义数据的结构化方式,然后可以使用特殊生成的源代码轻松地使用各种语言(C++/ C#/ Dart/ Go/ Java/ Kotlin/ Python)在各种数据流中写入和读取结构化数据。

安装

C++ Installation - Unix

最简单的方式:

sudo apt install protobuf-compiler

如果你想使用最新版,安装教程可以参考C++ Installation官网

Python

pip install protobuf

如果你想自己编译,安装教程可以参考Python Installation官网

环境

我用的是WSL,对于Linux类似,如果环境上有问题可以参考:【从零开始】在Windows中使用Linux——在WSL使用CLion、IDEA、PyCharm(安装到建立工程)——更新于2021.12

Protobuf3 0基础上手例子

我们从官网下载最新的Download Protocol Buffers(官方用例)作为例子如下:

使用PyCharm新建工程:
在这里插入图片描述
当前目录下创建addressbook.proto
在这里插入图片描述

// See README.txt for information and build instructions.
//
// Note: START and END tags are used in comments to define sections used in
// tutorials.  They are not part of the syntax for Protocol Buffers.
//
// To get an in-depth walkthrough of this file and the related examples, see:
// https://developers.google.com/protocol-buffers/docs/tutorials

// [START declaration]
syntax = "proto3";
package tutorial;

import "google/protobuf/timestamp.proto";
// [END declaration]

// [START java_declaration]
option java_multiple_files = true;
option java_package = "com.example.tutorial.protos";
option java_outer_classname = "AddressBookProtos";
// [END java_declaration]

// [START csharp_declaration]
option csharp_namespace = "Google.Protobuf.Examples.AddressBook";
// [END csharp_declaration]

// [START go_declaration]
option go_package = "../tutorial";
// [END go_declaration]

// [START messages]
message Person {
  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;
  }

  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]

创建文件add_person.py

#! /usr/bin/env python

# See README.txt for information and build instructions.

import addressbook_pb2
import sys

try:
    raw_input  # Python 2
except 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.
with open(sys.argv[1], "wb") as f:
    f.write(address_book.SerializeToString())

创建文件list_people.py

#! /usr/bin/env python

# See README.txt for information and build instructions.

from __future__ import print_function
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.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)

在PyCharm左下角打开Terminal:
在这里插入图片描述
输入:

protoc -I=./ --python_out=./ addressbook.proto

这时候我们会发现生成了以下文件:
在这里插入图片描述

之后,Run | Edit configuration 里添加 Python
在这里插入图片描述
我们点选run
在这里插入图片描述

然后在Run窗口里输入你想存入的数据:
在这里插入图片描述

同样的,Run | Edit configuration 里添加 Python
在这里插入图片描述
我们点选run
在这里插入图片描述

在Run窗口中会打印出我们刚才存入的数据:
在这里插入图片描述

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
protobuf序列化指的是用protobuf库将数据结构(如类、结构体、数组、列表等)转换成字节数组的过程。protobuf是一种轻量级的序列化框架,用于数据交换和存储领域。它具有协议缓冲区(Protocol Buffers)的特性,可实现高效的数据序列化和反序列化,支持多种编程语言(如C++、Java、Python等),有着简单、高效、扩展性强的优点,广泛应用于分布式系统、网络通信、数据存储、机器学习等领域。 protobuf序列化的过程包括定义数据结构、编写.proto文件、生成对应编程语言的代码、序列化和反序列化。定义数据结构时,需按protobuf规范定义字段类型和名称,如int、double、string、bool等,还可以定义嵌套类型、枚举类型等。编写.proto文件时,需遵循protobuf规范,指定消息类型、字段名称和编号、数据类型、默认值等信息,可以使用注释、枚举类型、嵌套类型等。生成代码时,需先安装protobuf库,然后用protoc命令编译.proto文件,生成对应编程语言的代码文件,如C++的.pb.h和.pb.cc文件、Java的.proto文件和.java文件等。序列化时,需先创建消息对象、设置字段值、调用SerializeToArray函数将消息对象序列化成字节数组。反序列化时,需先创建消息对象、调用ParseFromArray函数将字节数组反序列化成消息对象、获取字段值。 protobuf序列化具有以下优点:1)高效:protobuf序列化后的字节数组较小,序列化和反序列化效率高,占用的内存较少,可减少网络传输和存储开销;2)扩展性强:protobuf支持版本控制和兼容性,修改数据结构时不需要重写代码,只需修改.proto文件并重新编译即可;3)跨平台性好:protobuf支持多种编程语言,可在不同平台上使用同一套数据结构和代码;4)易维护:protobuf代码结构清晰,可读性好,易于维护和修改。 总之,protobuf序列化是一种高效、可扩展、跨平台、易维护的数据序列化方式,可广泛应用于各种领域的数据交换和存储。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值