Python 3中的协议缓冲区-NotImplementedError

Eip*_*ifi 5 python protocol-buffers python-3.x

我正在尝试在Python 3项目中使用Google协议缓冲区。但是,生成的python文件不想与google.protobuf库配合使用。尝试使用protobuf对象会导致NotImplementedError。

我的设置:

  • 的Python 3.4.1
  • 协议2.5.0

使用这些库时出现问题:

例:

from pb_test import test_pb2
pb_object = test_pb2.TestMsg()
pb_object.Clear()  # results in NotImplementedError
Run Code Online (Sandbox Code Playgroud)

当使用两个不同的库时,会出现相同的问题,这强烈表明存在无效的test_pb2.py文件。“未实现”的方法位于Message类中,该类应该被元类覆盖。似乎根本没有应用元类。

test.proto文件:

message TestMsg {
  required int32 id = 1;
}
Run Code Online (Sandbox Code Playgroud)

使用以下命令编译文件:

eipifi@debvm:~/pb_test$ protoc --python_out=. test.proto
Run Code Online (Sandbox Code Playgroud)

任何提示将不胜感激。

Eip*_*ifi 5

解决了。为了使 *_pb2.py 文件与 Python 3 中的 protobuf 库良好配合,需要按以下方式更改文件:

原来的:

class TestMsg(_message.Message):
__metaclass__ = _reflection.GeneratedProtocolMessageType
DESCRIPTOR = _TESTMSG
Run Code Online (Sandbox Code Playgroud)

固定的:

class TestMsg(_message.Message, metaclass=_reflection.GeneratedProtocolMessageType):
DESCRIPTOR = _TESTMSG
Run Code Online (Sandbox Code Playgroud)