protobuf - 多文件编译

Overview

对多个proto文件同时编译;指定include目录或out目录。

文件

命令

s$ ls
out  src
$ ls src/
bar.proto  foo.proto
$ ls out/
$ protoc -I=./src --python_out=./out ./src/*.proto
$ ls 
out  src
$ ls out/
bar_pb2.py  foo_pb2.py
$ 

foo.proto

syntax = "proto2";

message foo 
{ 
    required string    name = 1;
    required int32     id = 2;
    optional string    comment = 3;
}

bar.proto

syntax = "proto2";

import "foo.proto";

message bar 
{ 
    required string    name = 1;
    required int32     id = 2;
    optional string    comment = 3;
    optional foo       foo2 = 4;
}

Python Code (src/test.py)

#!/usr/bin/python

'''
src$ ./test.py 
serialized string: 0a0342617210011a0f42617220436f6d
                   6d656e74202e2e2e22180a03466f6f10
                   021a0f466f6f20436f6d6d656e74202e
                   2e2e
parsed object: name: "Bar"
id: 1
comment: "Bar Comment ..."
foo {
  name: "Foo"
  id: 2
  comment: "Foo Comment ..."
}

src$ hexdump -C temp.dat
00000000  0a 03 42 61 72 10 01 1a  0f 42 61 72 20 43 6f 6d  |..Bar....Bar Com|
00000010  6d 65 6e 74 20 2e 2e 2e  22 18 0a 03 46 6f 6f 10  |ment ..."...Foo.|
00000020  02 1a 0f 46 6f 6f 20 43  6f 6d 6d 65 6e 74 20 2e  |...Foo Comment .|
00000030  2e 2e                                             |..|
00000032
src$ 
'''

import binascii

import sys
sys.path.append("../out")
import foo_pb2
import bar_pb2

bar = bar_pb2.bar()
bar.name = "Bar"
bar.id = 1
bar.comment = "Bar Comment ..."
bar.foo.name = "Foo"
bar.foo.id = 2
bar.foo.comment = "Foo Comment ..."

s = bar.SerializeToString()

f = open("temp.dat", "wb")
f.write(s)
f.close()

print "serialized string:", 
print binascii.b2a_hex(bytearray(s))

bar2 = bar_pb2.bar()
bar2.ParseFromString(s)
print "parsed object:", bar2 

说明

这里把pb2.py放在out目录,仅仅是为了演示include, out等目录设置的方法。实际项目中不建议这种做法。

猜你喜欢

转载自blog.csdn.net/u013344915/article/details/77074550