0

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

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

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, '', '')

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

我使用 Python 3.7.4

我不知道该怎么办。

4

1 回答 1

0

您不能多次从管道中读取,因此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)
于 2019-10-10T21:28:46.377 回答