如何从 python 子进程中检索输出

How to retrive output from python subprocess

我正在使用 Python 子进程函数,因为我想在实时流中读取命令的输出。

但我希望在流程结束后,所有作为流输出写入的内容都完全返回给对象。

import subprocess
import shlex

def run_command(command):
    process = subprocess.Popen(str.split(command), stdout=subprocess.PIPE, stderr = subprocess.PIPE, encoding="utf-8", shell=True)
    while True:
        output = process.stdout.readline()
        if output == '' and process.poll() is not None:
            break
        if output:
            print(output.strip())
    out, err = process.communicate()
    return (process.returncode, out, err)

command_output = run_command("ping 8.8.8.8")
print(command_output)

实际结果:

Pinging 8.8.8.8 with 32 bytes of data:
Reply from 8.8.8.8: bytes=32 time=12ms TTL=57
Reply from 8.8.8.8: bytes=32 time=15ms TTL=57
Reply from 8.8.8.8: bytes=32 time=15ms TTL=57
Reply from 8.8.8.8: bytes=32 time=16ms TTL=57

Ping statistics for 8.8.8.8:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 12ms, Maximum = 16ms, Average = 14ms
(0, '', '')

我只得到完成过程的代码状态。 标准输出为空,但应该包含已处理命令的所有输出。

我用的是Python3.7.4

我不知道该怎么办。

您不能多次从管道读取,因此在完成后调用 process.communicate() 将不允许您再次读取 stdout

你应该简单地把你读到的所有输出都写成一个字符串。

def run_command(command):
    process = subprocess.Popen(str.split(command), stdout=subprocess.PIPE, stderr = subprocess.PIPE, encoding="utf-8", shell=True)
    all_output = ''
    while True:
        output = process.stdout.readline()
        if output == '' and process.poll() is not None:
            break
        if output:
            all_output += output
            print(output.strip())
    out, err = process.communicate()
    return (process.returncode, all_output, err)