Protocol Buffers in Python 3

I am trying to use Google Protocol Buffers in a Python 3 project. However the generated python files do not want to cooperate with the google.protobuf library. Trying to use the protobuf objects results in a NotImplementedError.

My setup:

  • Python 3.4.1
  • protoc 2.5.0
  • The problem appears when using these libraries:

  • protobuf-py3 (https://pypi.python.org/pypi/protobuf-py3/2.5.1)
  • python3-protobuf (https://pypi.python.org/pypi/python3-protobuf/2.5.0)
  • Example:

    from pb_test import test_pb2
    pb_object = test_pb2.TestMsg()
    pb_object.Clear()  # results in NotImplementedError
    

    The fact that the same problem occurs when using two different libraries is a strong hint towards having an invalid test_pb2.py file. The 'unimplemented' methods are located in Message class, which is supposed to be overridden by metaclass. It seems that the metaclass is not applied at all.

    The test.proto file:

    message TestMsg {
      required int32 id = 1;
    }
    

    The file is compiled using this command:

    eipifi@debvm:~/pb_test$ protoc --python_out=. test.proto
    

    Any hints would be appreciated.


    Solved. In order to make the *_pb2.py files play well with the protobuf libraries in Python 3, the files need to be changed in a following way:

    Original:

    class TestMsg(_message.Message):
    __metaclass__ = _reflection.GeneratedProtocolMessageType
    DESCRIPTOR = _TESTMSG
    

    Fixed:

    class TestMsg(_message.Message, metaclass=_reflection.GeneratedProtocolMessageType):
    DESCRIPTOR = _TESTMSG
    
    链接地址: http://www.djcxy.com/p/48338.html

    上一篇: 写/读协议缓冲区

    下一篇: Python 3中的协议缓冲区