为什么使用Google Protocol Buffers时会出现“无法导入名称descriptor_pb2”的错误?
在使用我们从protobuf类生成的Python代码时,出现了这个错误:
cannot import name descriptor_pb2
而相应的C++生成代码运行得很好,所以看起来我们的proto定义没有问题。
这个错误发生在我尝试导入我们的类时,像这样:
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
- 我们使用的是最新版本,所以我认为没有缺少任何文件。
有没有人知道解决办法是什么?
5 个回答
3
请确保按照说明文件中的指示安装protobuf运行库。你不能直接使用包里的源代码,因为descriptor_pb2.py需要通过protoc(protobuf编译器)生成,这是安装过程的一部分。
5
在我的情况下,找不到descriptor_pb2是因为protobuf没有正确安装。 在protobuf的python子目录下,确保运行以下命令:
python setup.py build
python setup.py test
python setup.py install (as root)
9
我觉得你需要自己用 protoc
来生成 descriptor_pb2.py
文件:
protoc descriptor.proto --python_out=gen/
gen/
是一个存放生成的 Python 类的文件夹。
之后,下面的内容就可以正常使用了:
sys.path.append('../gen')
from descriptor_pb2 import FileDescriptorSet
必须存在 ../gen/descriptor_pb2.py
这个文件。