grpc编译

python -m grpc_tools.protoc --python_out=. --grpc_python_out=. -I. routeguide.proto

转载https://www.jianshu.com/p/43fdfeb105ff?from=timeline&isappinstalled=0

https://blog.youkuaiyun.com/qq_42363032/article/details/115282405

### 编译 gRPC 生成代码的命令 在使用 gRPC 开发应用程序时,通常需要将 `.proto` 文件编译为特定语言的代码。以下是几种常见语言的编译命令示例。 #### Go 语言编译 gRPC 代码 要为 Go 语言编译 gRPC 服务代码,可以使用如下命令: ```bash protoc --go_out=. --go_opt=paths=source_relative \ --go-grpc_out=. --go-grpc_opt=paths=source_relative \ ./*.proto ``` 此命令会生成 Go 的普通 protobuf 代码和 gRPC 相关代码[^2]。 #### Go 语言编译 gRPC-Gateway 如果还需要生成 gRPC-Gateway 代码以支持 RESTful 接口,则可以使用以下命令: ```bash protoc \ --go_out . --go_opt paths=source_relative \ --go-grpc_out . --go-grpc_opt paths=source_relative \ --grpc-gateway_out . --grpc-gateway_opt paths=source_relative \ ./proto/rest.proto ``` 该命令将同时生成 gRPCgRPC-Gateway 所需的 Go 代码。 #### Python 语言编译 gRPC 代码 对于 Python 语言,可以通过如下方式调用 `protoc` 来生成代码: ```python import pkg_resources import sys from grpc_tools import _protoc_compiler def main(command_arguments): """Run the protocol buffer compiler with the given command-line arguments. Args: command_arguments: a list of strings representing command line arguments to `protoc`. """ command_arguments = [argument.encode() for argument in command_arguments] return _protoc_compiler.run_main(command_arguments) proto_include = pkg_resources.resource_filename('grpc_tools', '_proto') argv=['', '-I.', '--python_out=.', '--grpc_python_out=.', './helloworld.proto'] main(argv + ['-I{}'.format(proto_include)]) ``` 这段 Python 脚本展示了如何通过编程方式调用 `protoc` 工具来生成 PythongRPC 代码[^4]。 #### 注意事项 当使用较新版本的 `protoc-gen-go` 插件时,可能会遇到 `mustEmbedUnimplementedHelloServer` 错误。解决这个问题的方法之一是在服务实现中嵌入 `UnimplementedHelloServer` 结构体;另一种方法是在生成代码时不强制要求这个结构体: ```bash protoc --go-grpc_out=require_unimplemented_servers=false[,other options...]:. ``` 这样就可以避免必须实现 `mustEmbedUnimplementedHelloServer` 方法的问题[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值