簡體   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