安装遇到的问题
按官网推荐的做法,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
参考自:
简单的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