简体   繁体   中英

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. 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. 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:

import grpc_tools.protoc
grpc_tools.protoc.main(['protoc', '-I.', '--python_out=.', 'foo.proto'])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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