尝试在 Python 中导入生成的 gRPC 模块时遇到 ModuleNotFoundError。
在我的项目中,我有这样的文件结构:
from test.api.grpc_test_cases.specific_folder.api_pb2
这是我的协议命令的样子:
python3 \
-m grpc_tools.protoc \
-I proto_files \
--python_out=. \
--grpclib_python_out=. \
D.proto
python3 \
-m grpc_tools.protoc \
-I proto_files \
--python_out=. \
--grpclib_python_out=. \
proto_files/A.proto \
proto_files/B.proto \
proto_files/C.proto
在我的测试文件中,当我尝试导入生成的 pb2 文件时,出现以下错误:
ModuleNotFoundError: No module named 'api_pb2'
这是我尝试导入它的方法:
from file.innerfile.innermostfile.api.api_pb2 import ServiceRequest
我尝试了多种方法来解决此问题,包括:
我预计其中一种方法可以解决 ModuleNotFoundError 问题,从而允许我导入 ServiceRequest 以在我的 pytest 测试中使用而不会出现任何错误。我想使用 pb2 文件中的
ServiceRequest
使用 pytest 创建响应对象,如下所示:
response = ServiceRequest()
response.name = "John"
response.id = 123
response.timestamp = "2023-09-18T12:00:00"
因为protoc的路径逻辑取决于proto文件的位置。
正确的方法是让proto文件与要生成的python文件的路径位于同一文件夹中。
示例:
service
├── main.py
└── proto/
├── __init__.py
├── api.proto
├── api_pb2.py
└── api_pb2_grpc.py
协议-I。 --python_out=. --grpc_python_out=. ./proto/api.proto
所有
.
相对于原型文件的位置。