7

当使用从我们的 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\protobuf目录descriptor_pb2.py但只找到descriptor.py了 - 我们使用的是最新版本,所以我假设我们没有丢失任何文件。

有谁知道解决方案是什么?

4

5 回答 5

9

我相信你必须自己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必须存在。

于 2009-12-01T19:59:07.950 回答
5

在我的例子中,因为 protobuf 没有正确安装,所以没有找到 descriptor_pb2。在protobuf的python子目录下,一定要运行

python setup.py build
python setup.py test
python setup.py install (as root)
于 2013-12-05T15:29:28.587 回答
2

请确保按照自述文件中的说明安装 protobuf 运行时库。您不能简单地直接使用包中的源代码,因为descriptor_pb2.py 需要由protoc(protobuf 编译器)作为安装过程的一部分生成。

于 2009-12-01T21:36:48.697 回答
1

我在 Windows 10 上使用 python 2.7。

就我而言,我已经从https://github.com/google/protobuf/releases下载了 protoc-3.0.0-beta-2-win32并将二进制 protoc 文件复制到 src 文件夹。

之后,我运行了命令python setup.py build并生成了descriptor_pb2。

于 2016-04-07T14:11:47.980 回答
0

python setup.py 构建

此步骤是强制性的,因为它生成了一些源文件。

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

正是“descriptor_pb2.py”

于 2015-08-07T17:14:56.040 回答