将标准输入传递给 grpc_tools.protoc 和 --decode 选项用法

问题描述 投票:0回答:1

使用 grpc_tools.protoc 调用 --help 时 --decode 选项的用法摘要提到该选项从标准输入读取一些二进制文件并将其作为文本写入标准输出。我目前正在尝试解码某些

.pb
文件的内容,并使用
grpc_tools.protoc.main()
将标准输出传输到某些文本文件。虽然这通常可以通过
protoc --decode=a.b.message_type file.proto < file.pb > file.txt
完成,但我希望在 Python 中完成这一切,并且不知道如何将
.pb
文件的内容传递给
grpc_tools.protoc.main()

我尝试了以下实现,但它不起作用,因为

grpc_tools.protoc
.pb
文件参数解释为
.proto
文件:

grpc_tools.protoc.main(['protoc', '--decode=a.b.message_type', '--proto_path=./relative/path/to/proto', 'file.proto', 'path/to/file.pb'])

上面返回一个错误,指出 protoc.py“无法使原始路径相对:/path/to/file.pb”。

在上述命令中将

.pb
的路径作为附加选项包含在
--proto_path=./relative/path/to/pb
中,可以运行
grpc_tools.protoc.main()
,但它无法正确解码
.pb
文件的内容,因为它已将其解释为
.proto 
文件并向我发出警告:“没有为原始文件指定语法:file.pb。

我期待有一些选项或方法可以将

.pb
文件的内容传递到
grpc_tools.protoc.main()
,但我找不到任何相关文档。

protocol-buffers grpc-python
1个回答
0
投票

类似:

import subprocess

proto_path = "path/to/protoc"
proto_file = f"{proto_path}/file.proto"

service = "a.b"
message = "message_type"

command = [
    "python3",
    "-m",
    "grpc_tools.protoc",
    f"--proto_path={proto_path}",
    f"--decode={service}.{message}",
    proto_file,
]

with open("/path/to/file.pb", "r") as pb, open("/path/to/file.msg", "w") as m:
    subprocess.run(
        command,
        stdin=pb,
        stdout=m,
        check=True,
    )
© www.soinside.com 2019 - 2024. All rights reserved.