为什么我看到“cannot import name descriptor_pb2"使用 Google Protocol Buffers 时出错? [英] Why do I see "cannot import name descriptor_pb2" error when using Google Protocol Buffers?

查看:209
本文介绍了为什么我看到“cannot import name descriptor_pb2"使用 Google Protocol Buffers 时出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用从我们的 protobuf 类中生成的 Python 代码时,我们收到此错误:

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

cannot import name descriptor_pb2

等效的 C++ 生成的代码工作得很好,所以看起来我们的实际 proto 定义没有问题.

The equivalent C++ generated code works just fine, so it would appear that there is no problem with our actual proto definitions.

当我尝试导入我们的类时发生此错误,如下所示:

This error occurs when I try and import our class, like so:

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

from foobar_pb2 import FooBar

附加系统路径是否正确?

Is it correct to append the system paths?

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

I checked in the protobuf\python\google\protobuf directory for descriptor_pb2.py but only found descriptor.py - we're using the latest version, so I assume we don't have any files missing.

有人知道解决方案是什么吗?

Does anyone know what the solution is?

推荐答案

我相信你必须自己用 protoc 生成 descriptor_pb2.py :

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

protoc descriptor.proto --python_out=gen/

gen/ 是一个包含生成的 Python 类的文件夹.

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 必须存在.

这篇关于为什么我看到“cannot import name descriptor_pb2"使用 Google Protocol Buffers 时出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆