我想使用 protoc.main(...)
在运行时生成 python gRPC 文件,如下所示。
from grpc_tools import protoc
args = "--proto_path=. --python_out=grpc --grpc_python_out=grpc alpha.proto"
result = protoc.main(c)
上面的代码给出了“缺少输出指令”错误,结果代码为1
。
但是,下面的解决方法可以将 alpha.proto
作为命令行参数。这意味着 alpha.proto 文件没问题。
import subprocess
result = subprocess.call("python -m grpc_tools.protoc " + args, shell=True)
可能的原因是 (1) protoc.main
对每个字符进行编码,如下代码所示,或 (2) protoc.main
错误地解析内部参数路径。
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)
如何正确使用protoc.main
?
最佳答案
下面的代码将在 .proto
文件所在的 proto
目录中生成 python 文件。
proto_files = ["proto/file1.proto", "proto/file2.proto"]
from grpc_tools import protoc
for file in proto_files:
grpc_tools.protoc.main([
'grpc_tools.protoc',
'--proto_path=.',
'--python_out=.',
'--grpc_python_out=.',
file
])
我从答案中得到了提示; https://stackoverflow.com/a/54236739/361100
关于python - grpcio-tools protoc.main 给出 'missing output directives' 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57868551/