python protobuf 实践

安装遇到的问题

按官网推荐的做法,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 darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import code_pb2
Traceback (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 ExchangeKeyReq
from protobuf.exchange_key_pb2 import ExchangeKey
from binascii import unhexlify
from codecs import encode


def 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 s


request = ExchangeKeyReq()
request.N = str(long_to_bytes(325632573527326736248362483684835785))
request.E = 635531
exchange_key = ExchangeKey()
exchange_key.exchange_key_req.CopyFrom(request)
transfer = exchange_key.SerializeToString()

out = ExchangeKey()
out.ParseFromString(transfer)
print out
print 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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值