python操作protobuf

1.windows下安装

   1.从官网下载源码包解压进入vsproject,使用visual studio 打开解决方案,选择protoc生成解决方案会在Debug目录下生成protoc.exe

   2.不用源码包安装,可以直接在官网下载protoc.exe

   3.设置环境变量D:\

   4.进入python目录 执行python setup.py build 然后执行python setup.py install (readme说明里先执行python setup.py test  后执行python setup.py install )

2.使用

    1.编写proto文件

        

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 phone = 4;
}

message AddressBook {
  repeated Person person = 1;
}
    2.使用protoc.exe 生成py文件

       

protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/addressbook.proto
    会在目录生成addressbook_pb2.py文件

   3.编写add_person.py文件

#! /usr/bin/python

# See README.txt for information and build instructions.

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.phone.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] + ": File not found.  Creating a new file."

# Add an address.
PromptForAddress(address_book.person.add())

# Write the new address book back to disk.
f = open(sys.argv[1], "wb")
f.write(address_book.SerializeToString())
f.close()
  运行后报错:ImportError: cannot import name enum_type_wrapper(此错误信息针对2.5.0版本,2.3.0版本没有问题)

   解决方法:

                   1.修改setup.py文件168行添加一行代码

                      

'google.protobuf.internal.enum_type_wrapper',
                   2.重新build 和install


你可能感兴趣的:(python操作protobuf)