Python:从subprocess.call捕获stdout

dor*_*emi 6 python

我在使用Python执行shell cmd时尝试做两件事:

  • 捕获标准输出并在发生时将其打印出来
  • 捕获整个stdout并在cmd完成时处理它

我看了一下subprocess.check_output,但它没有stdout参数,可以让我在输出时打印输出.

所以在看完这个问题后,我意识到我可能需要尝试不同的方法.

from subprocess import Popen, PIPE

process = Popen(task_cmd, stdout = PIPE)
stdout, stderr = process.communicate()

print(stdout, stderr)
Run Code Online (Sandbox Code Playgroud)

这种方法的问题在于根据文档,Popen.communicate():

从stdout和stderr读取数据,直到达到文件结尾.等待进程终止

我似乎仍然无法将输出重定向到stdout和某种缓冲区,可以在命令完成时解析.

理想情况下,我喜欢这样的东西:

# captures the process output and dumps it to stdout in realtime
stdout_capture = Something(prints_to_stdout = True)
process = Popen(task_cmd, stdout = stdout_capture)

# prints the entire output of the executed process
print(stdout_capture.complete_capture)
Run Code Online (Sandbox Code Playgroud)

有没有推荐的方法来实现这一目标?

Jas*_*son -2

from subprocess import check_output, CalledProcessError

def shell_command(args):
    try:
        res = check_output(args).decode()
    except CalledProcessError as e:
        res = e.output.decode()
    for r in ['\r', '\n\n']:
        res = res.replace(r, '')
    return res.strip()
Run Code Online (Sandbox Code Playgroud)