为什么我会看到“不能导入名称descriptor_pb2”错误使用谷歌协议缓冲时?

StackOverflow https://stackoverflow.com/questions/1828379

  •  11-09-2019
  •  | 
  •  

在使用我们的protobuf类生成的Python代码,我们得到这个错误:

cannot import name descriptor_pb2

在相当于C ++生成的代码工作得很好,所以这样看来,有一个与我们的实际原定义没有问题。

当我尝试导入我们的类,出现此错误,像这样:

import sys
sys.path.append('..\path\to\generated')
sys.path.append('..\contrib\protobuf\python')

from foobar_pb2 import FooBar

是否正确追加系统路径?

我在protobuf\python\google\protobufdescriptor_pb2.py目录检查但只找到descriptor.py - 我们使用了最新的版本,所以我想我们没有任何文件丢失

有谁知道解决办法是什么?

有帮助吗?

解决方案

我相信你有生成descriptor_pb2.py protoc自己:

protoc descriptor.proto --python_out=gen/

gen/是与所生成的Python类的文件夹。

之后,将以下工作得很好:

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

../gen/descriptor_pb2.py必须存在。

其他提示

在我的情况下,发生找不到descriptor_pb2因为protobuf的安装不正确。 在protobuf的的蟒子目录,一定要运行

python setup.py build
python setup.py test
python setup.py install (as root)

请确保安装protobuf的运行时库中的指示自述文件。不能简单地使用源直接从包装中取出,因为descriptor_pb2.py需要由protoc(在protobuf的编译器)作为安装过程的一部分生成。

我使用Python 2.7上窗10。

/:

在我的情况下,我已经从 HTTPS下载protoc-3.0.0-β-2-的win32 /github.com/google/protobuf/releases 和复制的二进制protoc文件src文件夹。

后,我已经运行的命令的蟒setup.py构建生成和descriptor_pb2。

蟒setup.py构建

此步骤是必需的,因为它产生了一些源文件。

  

生成谷歌/ protobuf的/ descriptor_pb2.py ...生成   谷歌/ protobuf的/编译器/ plugin_pb2.py ...生成   谷歌/ protobuf的/ unittest_pb2.py ...生成   谷歌/ protobuf的/ unittest_custom_options_pb2.py ...生成   谷歌/ protobuf的/ unittest_import_pb2.py ...生成   谷歌/ protobuf的/ unittest_import_public_pb2.py ...生成   谷歌/ protobuf的/ unittest_mset_pb2.py ...生成   谷歌/ protobuf的/ unittest_no_generic_services_pb2.py ...生成   谷歌/ protobuf的/内部/ descriptor_pool_test1_pb2.py ...生成   谷歌/ protobuf的/内部/ descriptor_pool_test2_pb2.py ...生成   谷歌/ protobuf的/内部/ test_bad_identifiers_pb2.py ...生成   谷歌/ protobuf的/内部/ missing_enum_values_pb2.py ...生成   谷歌/ protobuf的/内部/ more_extensions_pb2.py ...生成   谷歌/ protobuf的/内部/ more_extensions_dynamic_pb2.py ...生成   谷歌/ protobuf的/内部/ more_messages_pb2.py ...生成   谷歌/ protobuf的/内部/ factory_test1_pb2.py ...生成   谷歌/ protobuf的/内部/ factory_test2_pb2.py ...生成   谷歌/ protobuf的/ pyext / python_pb2.py ... ... BLA

正的 'descriptor_pb2.py'

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top