Python 3中的协议缓冲区 - NotImplementedError
我在一个Python 3项目中尝试使用Google的协议缓冲区(Protocol Buffers)。但是生成的Python文件和google.protobuf库不太配合。使用protobuf对象时会出现一个叫做NotImplementedError的错误。
我的环境设置:
- Python 3.4.1
- protoc 2.5.0
这个问题出现在使用以下库时:
- protobuf-py3 (https://pypi.python.org/pypi/protobuf-py3/2.5.1)
- python3-protobuf (https://pypi.python.org/pypi/python3-protobuf/2.5.0)
示例代码:
from pb_test import test_pb2
pb_object = test_pb2.TestMsg()
pb_object.Clear() # results in NotImplementedError
同样的问题在使用两个不同的库时都出现,这很可能是因为test_pb2.py文件有问题。'未实现'的方法在Message类中,这个类应该被元类(metaclass)覆盖。但看起来元类根本没有应用。
test.proto文件内容:
message TestMsg {
required int32 id = 1;
}
这个文件是通过以下命令编译的:
eipifi@debvm:~/pb_test$ protoc --python_out=. test.proto
任何提示都会很有帮助。
1 个回答
5
解决了。为了让 *_pb2.py 文件能够和 Python 3 中的 protobuf 库正常工作,需要对这些文件进行以下修改:
原始内容:
class TestMsg(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _TESTMSG
修复后的内容:
class TestMsg(_message.Message, metaclass=_reflection.GeneratedProtocolMessageType):
DESCRIPTOR = _TESTMSG