从同一个 .proto 文件生成 Python 和 Go 代码 - 导入问题
Generating Python and Go code from the same .proto file - problem with imports
我很难为 Python 和 Go 使用共享的 .proto 文件生成代码。有问题的部分是我正在使用 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
完整的原型文件路径为:
/usr/local/Cellar/protobuf/3.7.1/include/google/protobuf/timestamp.proto
您可以看到 gRPC 安装附带的其他标准原型定义,例如 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 工具包(及其 headers),那么上述目录层次结构应该与任何 OS 构建相匹配.
P.S。此 question 解释了如何在使用 proto-compiler.
时设置显式 INCLUDE_PATH
我很难为 Python 和 Go 使用共享的 .proto 文件生成代码。有问题的部分是我正在使用 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
完整的原型文件路径为:
/usr/local/Cellar/protobuf/3.7.1/include/google/protobuf/timestamp.proto
您可以看到 gRPC 安装附带的其他标准原型定义,例如 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 工具包(及其 headers),那么上述目录层次结构应该与任何 OS 构建相匹配.
P.S。此 question 解释了如何在使用 proto-compiler.
时设置显式INCLUDE_PATH