如何获取包含管道的 Python 子进程命令的输出? [英] How can I get the output of a Python subprocess command that contains a pipe?

查看:20
本文介绍了如何获取包含管道的 Python 子进程命令的输出?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有:

cmd_array = ['head', '-n', str(source_noise_end), "data/noise/" + source + '_16k.dat', '|', 'tail', '-' + str(source_noise_start)]
source_noise = subprocess.check_output(cmd_array)

该命令在我输入 Linux 时有效.我得到 subprocess.CalledProcessError: Command '['head', '-n', '2366468', 'data/noise/white_16k.dat', '|', 'tail', '-2183988']' 返回非零退出状态 1.

The command is valid when I type it into Linux. I get subprocess.CalledProcessError: Command '['head', '-n', '2366468', 'data/noise/white_16k.dat', '|', 'tail', '-2183988']' returned non-zero exit status 1.

我做错了什么?

推荐答案

试试这个:

import subprocess

# cmd contains shell command
cmd="your command shell"

process = subprocess.Popen(cmd,shell=True,stdin=None,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# The output from your shell command
result=process.stdout.readlines()
if len(result) >= 1:
    for line in result:
        print(line.decode("utf-8"))

这篇关于如何获取包含管道的 Python 子进程命令的输出?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆