登录
首页 >  Golang >  Go问答

从同一个 .proto 文件生成 Python 和 Go 代码 - 导入问题

来源:stackoverflow

时间:2024-04-02 22:18:38 236浏览 收藏

Golang不知道大家是否熟悉?今天我将给大家介绍《从同一个 .proto 文件生成 Python 和 Go 代码 - 导入问题》,这篇文章主要会讲到等等知识点,如果你在看完本篇文章后,有更好的建议或者发现哪里有问题,希望大家都能积极评论指出,谢谢!希望我们能一起加油进步!

问题内容

我很难使用共享的 .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

完整的原型文件路径为:

/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 工具包(及其标头)安装在正确的位置,则上述目录层次结构应与任何操作系统版本匹配。

附注此 question 解释了如何在使用原始编译器时设置显式 include_path

到这里,我们也就讲完了《从同一个 .proto 文件生成 Python 和 Go 代码 - 导入问题》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>