在python中运行复杂的命令行

我想在Python中调用一个复杂的命令行并捕获其输出,但我不知道该怎么做:

我要运行的命令行是:

cat codegen_query_output.json | jq -r '.[0].code' | echoprint-inverted-query index.bin

据我所知:

process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE)
out, err = process.communicate()
print out

但这是一个简单的ls -a([cmd,args])任何想法我应该如何运行/结构化复杂的命令行调用?

让·弗朗索瓦·法布尔

最干净的方法是创建2个通过管道连接在一起的子流程。您不需要该cat命令的子进程,只需传递一个打开的文件句柄即可:

import subprocess

with open("codegen_query_output.json") as input_stream:
    jqp = subprocess.Popen(["jq","-r",'.[0].code'],stdin=input_stream,stdout=subprocess.PIPE)
    ep = subprocess.Popen(["echoprint-inverted-query","index.bin"],stdin=jqp.stdout,stdout=subprocess.PIPE)
    output = ep.stdout.read()
    return_code = ep.wait() or jqp.wait()

jqp过程将文件内容作为输入。它的输出传递到ep输入。

最后,我们从中读取输出ep以获得最终结果。return_code既是返回码的组合。如果出了什么问题,它不同于0(当然,更详细的返回码信息将单独进行测试)

这里不考虑标准错误。除非stderr=subprocess.STDOUT设置(与管道输出合并),它将显示在控制台上

此方法不需要shell或shell=True,因此更可移植且更安全。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章