【问题标题】:Running a complex command line in python在 python 中运行复杂的命令行
【发布时间】:2018-10-02 12:25:18
【问题描述】:

我想在 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]) 知道我应该如何运行/构建复杂的命令行调用吗?

【问题讨论】:

    标签: python python-2.7 shell command-line popen


    【解决方案1】:

    最简洁的方法是创建 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,因此更便携、更安全。

    【讨论】:

    • 效果非常好!我喜欢不需要使用 shell 的想法。
    【解决方案2】:

    解释operators like | 需要一个shell。你可以让 Python 运行一个 shell,并将你的命令作为要执行的东西传递:

    cmd = "cat test.py | tail -n3"                                                  
    process = subprocess.Popen(['bash', '-c', cmd], stdout=subprocess.PIPE)         
    out, err = process.communicate()                                                
    print out        
    

    【讨论】:

    • 我不能将两个答案都标记为好,这个版本也可以工作,虽然我喜欢以前的答案,因为我喜欢避免使用 bash 命令的想法。还是谢谢!!
    猜你喜欢
    • 2020-01-10
    • 2013-11-29
    • 1970-01-01
    • 1970-01-01
    • 2012-08-24
    • 2023-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多