我想使用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
如果您正在遵循 golang protobufs 的中等教程,请不要复制和粘贴:
protoc --go_out=. *.proto
命令,因为--
不是真正的-
(破折号等(,所以手动输入命令解决了我的问题。
由于复制和粘贴不正确的字符,我收到了此错误
我希望你从我愚蠢的错误中吸取教训:)