---
title: "protocal buffer 之Java与python交互"
author: "googya"
date: "2011-04-09T18:18:01Z"
tags: ["F#", "ITeye", "Java", "Mobile", "Python"]
categories: ["企业架构"]
slug: "protocal-buffer-java-python"
draft: false
lastmod: "2011-04-09T20:26:55Z"
id: 994814
url: "https://googya.iteye.com/blog/994814"
---

今天了解了一下protocal buffer，觉得这个协议还是比较有实用价值的。不同语言（当前只支持java，python和c++)可以对相同的模型进行操作，而且通过特殊的编码使得交互的数据量变得很小。当然，目前对这个协议了解得比较有限，还说不出什么一二三。下面是安装使用protocal buffer的过程。
        
        以下的操作都是在cygwin环境下面。      
        
        首先当然是安装。


        参照readme文件：
          $ ./configure
          $ make
          $ make check
          $ make install
        
        安装之后，进行检查，输入
         protoc --version
        我这里的结果是：
        libprotoc 2.4.0
        
        出现了版本号之后，就说明安装是正常的。
        

         java 接着是，生成jar包：
         
         mvn install
         
         安装 python包：
         $ python setup.py install
          
         全部完成之后，采用protocal buffer的例子（此处略去1000字）
         分别输出成java文件和py文件
         $ protoc -I=. --java_out=. ./addressbook.proto
         $ protoc -I=. --python_out=. ./addressbook.proto


         用Java添加信息到文件中：

```java


import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.io.PrintStream;

class AddPerson {
  // This function fills in a Person message based on user input.
  static Person PromptForAddress(BufferedReader stdin,
                                 PrintStream stdout) throws IOException {
    Person.Builder person = Person.newBuilder();

    stdout.print("Enter person ID: ");
    person.setId(Integer.valueOf(stdin.readLine()));

    stdout.print("Enter name: ");
    person.setName(stdin.readLine());

    stdout.print("Enter email address (blank for none): ");
    String email = stdin.readLine();
    if (email.length() > 0) {
      person.setEmail(email);
    }

    while (true) {
      stdout.print("Enter a phone number (or leave blank to finish): ");
      String number = stdin.readLine();
      if (number.length() == 0) {
        break;
      }

      Person.PhoneNumber.Builder phoneNumber =
        Person.PhoneNumber.newBuilder().setNumber(number);

      stdout.print("Is this a mobile, home, or work phone? ");
      String type = stdin.readLine();
      if (type.equals("mobile")) {
        phoneNumber.setType(Person.PhoneType.MOBILE);
      } else if (type.equals("home")) {
        phoneNumber.setType(Person.PhoneType.HOME);
      } else if (type.equals("work")) {
        phoneNumber.setType(Person.PhoneType.WORK);
      } else {
        stdout.println("Unknown phone type.  Using default.");
      }

      person.addPhone(phoneNumber);
    }

    return person.build();
  }

  // Main function:  Reads the entire address book from a file,
  //   adds one person based on user input, then writes it back out to the same
  //   file.
  public static void main(String[] args) throws Exception {
    if (args.length != 1) {
      System.err.println("Usage:  AddPerson ADDRESS_BOOK_FILE");
      System.exit(-1);
    }

    AddressBook.Builder addressBook = AddressBook.newBuilder();

    // Read the existing address book.
    try {
      addressBook.mergeFrom(new FileInputStream(args[0]));
    } catch (FileNotFoundException e) {
      System.out.println(args[0] + ": File not found.  Creating a new file.");
    }

    // Add an address.
    addressBook.addPerson(
      PromptForAddress(new BufferedReader(new InputStreamReader(System.in)),
                       System.out));

    // Write the new address book back to disk.
    FileOutputStream output = new FileOutputStream(args[0]);
    addressBook.build().writeTo(output);
    output.close();
  }
}



```

            编译执行。。。。。。


            之后用python读取
            
```Python


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.person:
    print "Person ID:", person.id
    print "  Name:", person.name
    if person.HasField('email'):
      print "  E-mail address:", person.email

    for phone_number in person.phone:
      if phone_number.type == addressbook_pb2.Person.MOBILE:
        print "  Mobile phone #: ",
      elif phone_number.type == addressbook_pb2.Person.HOME:
        print "  Home phone #: ",
      elif phone_number.type == addressbook_pb2.Person.WORK:
        print "  Work phone #: ",
      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.
f = open(sys.argv[1], "rb")
address_book.ParseFromString(f.read())
f.close()

ListPeople(address_book)



             
```



最后的结果如图：

         添加  ![](http://dl.iteye.com/upload/attachment/457161/93d977d2-da7e-378d-ba96-00ff17d611a0.jpg)

         读取　　![](http://dl.iteye.com/upload/attachment/457163/5c40f4d2-901d-3ed8-857d-7b445c9e7d8a.jpg)