繁体   English   中英

如何获取包含管道的 Python 子进程命令的输出?

[英]How can I get the output of a Python subprocess command that contains a pipe?

我有:

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']' 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"))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM