有什么方法可以在不使用子过程的情况下使用Python中的Protobuf编译器?
我正在编写一个脚本,该脚本应该越过我作为参数的路径,然后逐一编译所有.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)
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)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
grpcio_tools 软件包具有protoc作为函数:
The grpcio_tools package has protoc available as a function: