[英]Is there any way to use Protobuf compiler in python without using subprocess?
I'm writing a script that should run over a path I get as an argument, and compile all .proto files one by one.我正在编写一个脚本,该脚本应该在我作为参数获得的路径上运行,并逐个编译所有 .proto 文件。 Currently I'm using Popen to do that, but it makes sense that we could use the protobuf compiler from within python without using subprocesses.
目前我正在使用 Popen 来做到这一点,但我们可以在 python 中使用 protobuf 编译器而不使用子进程是有道理的。 any idea how to do so?
知道怎么做吗?
thanks!谢谢!
this is my current code:这是我当前的代码:
def dir_path(string):
if os.path.isdir(string):
return string
else:
raise NotADirectoryError(string)
def compProtos(frompath, topath):
for dirpath, dirs, files in os.walk(frompath):
for filename in files:
if filename.endswith('.proto'):
print(
f'Currently generating file: {filename}, from path: {dirpath}')
process = Popen(
f'python -m grpc_tools.protoc -I {dirpath} --python_out={topath} --grpc_python_out={topath} {dirpath}/{filename}')
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Run gRPC on protobuffs')
parser.add_argument('-from', dest="frompath", type=dir_path,
required=True, help="Enter protobuffs path", metavar="FILE")
parser.add_argument('-to', dest="topath", type=dir_path, default=".",
help="Enter saving path", metavar="FILE")
args = parser.parse_args()
compProtos(args.frompath, args.topath)
print("Done generating protobuffs, results in folder: " + args.topath)
The grpcio_tools package has protoc available as a function: grpcio_tools包有 protoc 作为函数:
import grpc_tools.protoc
grpc_tools.protoc.main(['protoc', '-I.', '--python_out=.', 'foo.proto'])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.