繁体   English   中英

有没有办法在不使用子进程的情况下在 python 中使用 Protobuf 编译器?

[英]Is there any way to use Protobuf compiler in python without using subprocess?

我正在编写一个脚本,该脚本应该在我作为参数获得的路径上运行,并逐个编译所有 .proto 文件。 目前我正在使用 Popen 来做到这一点,但我们可以在 python 中使用 protobuf 编译器而不使用子进程是有道理的。 知道怎么做吗?

谢谢!

这是我当前的代码:

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)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM