![](/img/trans.png)
[英]Any way to execute a piped command in Python using subprocess module, without using shell=True?
[英]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.