美文网首页
Python使用protobuf极简例子

Python使用protobuf极简例子

作者: 赤色要塞满了 | 来源:发表于2019-08-07 14:01 被阅读0次

    下载安装

    首先,可以直接到protobuf官网阅读学习,到protobuf的github下载编译器。对于非c++用户,直接到github release下载编译好的二进制文件,如果是windows,可以直接下载这个包,然后把bin/protoc.exe放到工作目录。

    编译proto文件

    目录下新建一个addressbook.proto文件,来自官网的例子(略减):

    syntax = "proto3";
    package tutorial;
    
    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;
    
    }
    
    message AddressBook {
      repeated Person people = 1;
    }
    

    然后运行protoc.exe

    protoc --python_out=./ addressbook.proto
    

    就直接在当前目录生成了一个addressbook_pb2.py

    测试

    先安装一下protocbuf模块,这不必多解释:

    pip install protobuf
    

    新建一个add_person.py,也是来自官网的例子(略改):

    import addressbook_pb2
    import sys
    
    
    def PromptForAddress(person):
        """For enter personal infomations"""
        person.id = int(input('Enter ID:'))
        person.name = input('Enter name:')
    
        email = input('Enter email:')
        if email:
            person.email = email
    
        while True:
            number = input('Enter phone number (or leave blank to finish):')
            if not number:
                break
    
            phone_number = person.phones.add()
            phone_number.number = number
    
            type_ = input('Is this a mobile(0), home(1), or work(2) phone?')
            if type_ == "0":
                phone_number.type = addressbook_pb2.Person.MOBILE
            elif type_ == "1":
                phone_number.type = addressbook_pb2.Person.HOME
            elif type_ == "2":
                phone_number.type = addressbook_pb2.Person.WORK
            else:
                print("Unknown phone type; leaving as default value.")
    
    
    if len(sys.argv) != 2:
        print('Usage:', sys.argv[0], "ADDRESS_BOOK_FILE")
        sys.exit(0)
    
    a = addressbook_pb2.AddressBook()
    try:
        with open(sys.argv[1], 'rb') as f:
            a.ParseFromString(f.read())
            print(a)
    except IOError:
        print(sys.argv[1] + ": not found")
    
    b = addressbook_pb2.AddressBook()
    person = b.people.add()
    PromptForAddress(person)
    
    with open(sys.argv[1], "ab") as f:
        f.write(b.SerializeToString())
    

    试运行一下:

    >> python add_person.py my_address_book.txt
    my_address_book.txt: not found
    Enter ID:1
    Enter name:Tom
    Enter email:tom@abc.com
    Enter phone number (or leave blank to finish):58881234
    Is this a mobile(0), home(1), or work(2) phone?2
    Enter phone number (or leave blank to finish):
    

    这样会把一条记录保存进二进制文件my_address_book.txt,注意,只能是二进制读写,无法直接打开。
    再运行,看看读取的效果:

    >> python add_person.py my_address_book.txt
    people {
      name: "Tom"
      id: 1
      email: "tom@abc.com"
      phones {
        number: "58881234"
        type: WORK
      }
    }
    
    Enter ID:
    

    搞定。

    相关文章

      网友评论

          本文标题:Python使用protobuf极简例子

          本文链接:https://www.haomeiwen.com/subject/myobdctx.html