我很难使用共享的 .proto 文件生成 Python 和 Go 的代码。有问题的部分是我正在利用 timestamp.proto
(由 google 提供),需要根据生成的代码应使用的语言以不同的方式导入它。
Python 代码生成器需要这种形式:
import "google/protobuf/timestamp.proto";
虽然 Go 代码生成器需要这样:
import "github.com/golang/protobuf/ptypes/timestamp/timestamp.proto";
是否可以使此导入对两种语言都有效?怎么办?
最佳答案
这个原始路径是错误的:
import "github.com/golang/protobuf/ptypes/timestamp/timestamp.proto"; // WRONG path
无论您使用什么语言 - Go 或 Python 等,这都是正确的导入路径:
import "google/protobuf/timestamp.proto"; // correct path for any language (go, python etc)
<小时/>
这个 timestamp.proto
文件由 protoc-gen-go
工具(生成 Go 代码时)使用其默认的 INCLUDE_PATH
定位。
例如,在我的 Mac 上,默认的 INCLUDE_PATH
是:
/usr/local/Cellar/protobuf/3.7.1/include
完整的原型(prototype)文件路径为:
/usr/local/Cellar/protobuf/3.7.1/include/google/protobuf/timestamp.proto
您可以查看 gRPC 安装附带的其他标准原型(prototype)定义,例如 duration.proto
:
$ pwd # my default gRPC include path
/usr/local/Cellar/protobuf/3.7.1/include
$ find . -name "*.proto"
./google/protobuf/timestamp.proto
./google/protobuf/field_mask.proto
./google/protobuf/api.proto
./google/protobuf/duration.proto
./google/protobuf/struct.proto
./google/protobuf/wrappers.proto
./google/protobuf/source_context.proto
./google/protobuf/any.proto
./google/protobuf/type.proto
./google/protobuf/empty.proto
./google/protobuf/compiler/plugin.proto
./google/protobuf/descriptor.proto
前提是您已按照 install docs 将 gRPC 工具包(及其 header )安装在正确的位置。 ,那么上述目录层次结构应该与任何操作系统版本匹配。
附注这个question解释了如何在使用原始编译器时设置显式 INCLUDE_PATH
。
关于python - 从同一个 .proto 文件生成 Python 和 Go 代码 - 导入问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58418450/