在 Python 中使用协议生成正确的导入
Generate correct import using protoc in Python
我在 python
项目中使用 proto3
。一切正常,但是当我从 proto
文件生成 类 时,导入不正确。
我有这样的目录结构。
project/endpoints/protos -> image.proto
我想要输出文件。
project/endpoints/grpc -> 从原型文件
生成类
我正在使用此命令从 proto
文件生成 类。
python -m grpc.tools.protoc \
--include_imports \
--include_source_info \
--proto_path=project/endpoints/protos \
--python_out=project/endpoints/grpc \
--grpc_python_out=project/endpoints/grpc \
image.proto
我也用 python3 ....
尝试过,但结果相同。
它在 project/endpoints/grpc
中生成文件,但问题是导入不正确。当我看到导入时,它看起来像。
import image_pb2 as image__pb2
但应该是这样的
import project.endpoints.grpc.image_pb2 as image__pb2
你能告诉我如何像这样生成导入吗?
经过大量研究
我找到了
in here
Mint 中的解决方案:
sudo apt-get install 2to3
运行调整进口:
2to3 path/of/generated -w -n
所以
import image_pb2
将更改为
from . import image_pb2
如果您需要:
from project.endpoints.grpc import image_pb2 as image__pb2
你应该在原型文件中这样写:
import "project/endpoints/grpc/image.proto"
然后将当前目录或--proto_path
设置为“项目”的父目录。
我在 python
项目中使用 proto3
。一切正常,但是当我从 proto
文件生成 类 时,导入不正确。
我有这样的目录结构。
project/endpoints/protos -> image.proto
我想要输出文件。
project/endpoints/grpc -> 从原型文件
生成类我正在使用此命令从 proto
文件生成 类。
python -m grpc.tools.protoc \
--include_imports \
--include_source_info \
--proto_path=project/endpoints/protos \
--python_out=project/endpoints/grpc \
--grpc_python_out=project/endpoints/grpc \
image.proto
我也用 python3 ....
尝试过,但结果相同。
它在 project/endpoints/grpc
中生成文件,但问题是导入不正确。当我看到导入时,它看起来像。
import image_pb2 as image__pb2
但应该是这样的
import project.endpoints.grpc.image_pb2 as image__pb2
你能告诉我如何像这样生成导入吗?
经过大量研究
我找到了 in here
Mint 中的解决方案:
sudo apt-get install 2to3
运行调整进口:
2to3 path/of/generated -w -n
所以
import image_pb2
将更改为
from . import image_pb2
如果您需要:
from project.endpoints.grpc import image_pb2 as image__pb2
你应该在原型文件中这样写:
import "project/endpoints/grpc/image.proto"
然后将当前目录或--proto_path
设置为“项目”的父目录。