如何获取包含管道的 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"))
相关文章