python protobuf 实践

来源:互联网 发布:政府网站域名后缀 编辑:程序博客网 时间:2024/06/01 08:26

安装遇到的问题

按官网推荐的做法,import报错

Python 2.7.13 (default, Dec 18 2016, 07:03:39) [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwinType "help", "copyright", "credits" or "license" for more information.>>> import code_pb2Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "code_pb2.py", line 11, in <module>    from google.protobuf import descriptor_pb2  File "/Users/yeshen/RobotsEnv/lib/python2.7/site-packages/protobuf-3.3.0-py2.7-macosx-10.12-x86_64.egg/google/protobuf/descriptor_pb2.py", line 1010, in <module>    options=None),  File "/Users/yeshen/RobotsEnv/lib/python2.7/site-packages/protobuf-3.3.0-py2.7-macosx-10.12-x86_64.egg/google/protobuf/descriptor.py", line 498, in __new__    return _message.default_pool.FindFieldByName(full_name)KeyError: "Couldn't find field google.protobuf.FileOptions.php_namespace"

解决办法:

pip install –force-reinstall –upgrade protobuf

参考自:

https://github.com/tensorflow/models/issues/940

简单的protobuf使用

exchange_key.proto

package protocol;option java_package = "org.yeshen.exchange";enum ENCRYPT_TYPE {    RC4 = 1;};message ExchangeKeyReq {    required bytes N = 1;    required int32 E = 2;}message ExchangeKeyRes {    required bytes key = 1;    required ENCRYPT_TYPE type = 2;}message ExchangeKey {    optional ExchangeKeyReq exchange_key_req = 1;    optional ExchangeKeyRes exchange_key_res = 2;}
protoc -I=$SRC_DIR --python_out=$DST_DIR $SRC_DIR/exchange_key.proto
from protobuf.exchange_key_pb2 import ExchangeKeyReqfrom protobuf.exchange_key_pb2 import ExchangeKeyfrom binascii import unhexlifyfrom codecs import encodedef long_to_bytes(value, endianness='big'):    # https://stackoverflow.com/questions/8730927/convert-python-long-int-to-fixed-size-byte-array    width = value.bit_length()    width += 8 - ((width % 8) or 8)    fmt = '%%0%dx' % (width // 4)    s = unhexlify(fmt % value)    if endianness == 'little':        # see http://stackoverflow.com/a/931095/309233        s = s[::-1]    return srequest = ExchangeKeyReq()request.N = str(long_to_bytes(325632573527326736248362483684835785))request.E = 635531exchange_key = ExchangeKey()exchange_key.exchange_key_req.CopyFrom(request)transfer = exchange_key.SerializeToString()out = ExchangeKey()out.ParseFromString(transfer)print outprint int(encode(out.exchange_key_req.N, 'hex'), 16)

python t.py

exchange_key_req {  N: ">\266\354\350U\215\216Z\335\276Ye\321\201\311"  E: 635531}325632573527326736248362483684835785
原创粉丝点击