Why do I see “cannot import name descriptor_pb2” error when using Google Protocol Buffers?

前端 未结 5 594
隐瞒了意图╮
隐瞒了意图╮ 2021-01-18 03:51

When using the generated Python code from our protobuf classes, we get this error:

cannot import name descriptor_pb2

The equivalent C++ gen

相关标签:
5条回答
  • 2021-01-18 03:59

    In my case, not finding descriptor_pb2 occurred because protobuf wasn't correctly installed. In the python subdirectory of protobuf, be sure to run

    python setup.py build
    python setup.py test
    python setup.py install (as root)
    
    0 讨论(0)
  • 2021-01-18 03:59

    python setup.py build

    This step is mandatory as it generated some of the source files.

    Generating google/protobuf/descriptor_pb2.py... Generating google/protobuf/compiler/plugin_pb2.py... Generating google/protobuf/unittest_pb2.py... Generating google/protobuf/unittest_custom_options_pb2.py... Generating google/protobuf/unittest_import_pb2.py... Generating google/protobuf/unittest_import_public_pb2.py... Generating google/protobuf/unittest_mset_pb2.py... Generating google/protobuf/unittest_no_generic_services_pb2.py... Generating google/protobuf/internal/descriptor_pool_test1_pb2.py... Generating google/protobuf/internal/descriptor_pool_test2_pb2.py... Generating google/protobuf/internal/test_bad_identifiers_pb2.py... Generating google/protobuf/internal/missing_enum_values_pb2.py... Generating google/protobuf/internal/more_extensions_pb2.py... Generating google/protobuf/internal/more_extensions_dynamic_pb2.py... Generating google/protobuf/internal/more_messages_pb2.py... Generating google/protobuf/internal/factory_test1_pb2.py... Generating google/protobuf/internal/factory_test2_pb2.py... Generating google/protobuf/pyext/python_pb2.py... bla...

    Precisely the 'descriptor_pb2.py'

    0 讨论(0)
  • 2021-01-18 04:13

    I believe you have to generate descriptor_pb2.py with protoc yourself:

    protoc descriptor.proto --python_out=gen/
    

    gen/ is a folder with generated python classes.

    After that, the following works just fine:

    sys.path.append('../gen')
    from descriptor_pb2 import FileDescriptorSet
    

    ../gen/descriptor_pb2.py must exists.

    0 讨论(0)
  • 2021-01-18 04:15

    Please make sure to install the protobuf runtime library as directed in the readme file. You cannot simply use the source directly out of the package, since descriptor_pb2.py needs to be generated by protoc (the protobuf compiler) as part of the installation process.

    0 讨论(0)
  • 2021-01-18 04:16

    I use python 2.7 on windows 10.

    In my case, I have downloaded protoc-3.0.0-beta-2-win32 from https://github.com/google/protobuf/releases and copied the binary protoc file to src folder.

    after that I have run the command python setup.py build and the descriptor_pb2 was generated.

    0 讨论(0)
提交回复
热议问题