protofile.proto: 池中已存在同名文件

protofile.proto: A file with this name is already in the pool

具有以下结构:

- project1
  - project1.py
  - protofile_pb2.py
  - protofile_pb2_grpc.py
- project2
  - project2.py
  - protofile_pb2.py
  - protofile_pb2_grpc.py

project1.py:

import protofile_pb2.py
...

project2.py:

import protofile_pb2
import project1
...

当 运行 project2.py 时,我得到这个错误:

TypeError: Couldn't build proto file into descriptor pool!
Invalid proto descriptor for file "protofile.proto":
protofile.proto: A file with this name is already in the pool.

您使用的是生成的 protofile.proto 的不同版本。确保重新生成 protobuf 文件,它应该可以正常工作。

根据 this comment,它对我有用:

pip uninstall protobuf
pip install --no-binary protobuf protobuf

我在 Python 中部署 google 云功能时遇到了类似的问题。我的云函数在我的模块中使用了不同版本的 .proto 文件(这又是一个我想使用 requirements.txt 安装的私有模块)。解决方案是使用纯 python 实现而不是使用 protobuf 的二进制实现。要在云函数或云构建中解决此问题,您可以设置云函数环境变量以使用协议缓冲区的 python 实现。

在您的 gcloud 云函数部署命令中使用以下选项:

<start of command> --set-env-vars=PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION='python' <your rest of the command>

或者如果您在任何其他 env/os 中,只需执行此操作

export PROTOCOL_BUFFERS_PYTHON_IMPLEMENTATION='python' 

这解决了我的问题。