mlczhg 发表于 2017-5-2 09:10:42

protocal buffer 之Java与python交互

今天了解了一下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添加信息到文件中:

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));
} catch (FileNotFoundException e) {
System.out.println(args + ": 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);
addressBook.build().writeTo(output);
output.close();
}
}


            编译执行。。。。。。

            之后用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, "ADDRESS_BOOK_FILE"
sys.exit(-1)
address_book = addressbook_pb2.AddressBook()
# Read the existing address book.
f = open(sys.argv, "rb")
address_book.ParseFromString(f.read())
f.close()
ListPeople(address_book)



最后的结果如图:
         添加
         读取  
页: [1]
查看完整版本: protocal buffer 之Java与python交互