python subprocess 想实时输出子进程的结果,但总是不全

终端的输出如下:

$>ping www.baidu.com -c5
PING www.a.shifen.com (61.135.169.125) 56(84) bytes of data.
64 bytes from 61.135.169.125: icmp_seq=1 ttl=54 time=4.47 ms
64 bytes from 61.135.169.125: icmp_seq=2 ttl=54 time=6.28 ms
64 bytes from 61.135.169.125: icmp_seq=3 ttl=54 time=3.92 ms
64 bytes from 61.135.169.125: icmp_seq=4 ttl=54 time=4.87 ms
64 bytes from 61.135.169.125: icmp_seq=5 ttl=54 time=6.44 ms

--- www.a.shifen.com ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4005ms
rtt min/avg/max/mdev = 3.923/5.201/6.448/1.001 ms

在python中用subprocess输出,始终没有最后那三行.

方法1:

def main():
    p = subprocess.Popen(['ping', 'www.baidu.com', '-c5'], stdin = subprocess.PIPE, stdout = subprocess.PIPE)
    while True: 
        r = p.stdout.readline().strip().decode('utf-8')
        if r:
            print(r)
        if subprocess.Popen.poll(p) != None and not r:
            break

方法2:

def main():
    p = subprocess.Popen(['ping', 'www.baidu.com', '-c5'], stdin = subprocess.PIPE, stdout = subprocess.PIPE)
    while subprocess.Popen.poll(p) == None:
        r = p.stdout.readline().strip().decode('utf-8')
        if r:
            print(r);
    print(p.stdout.readline().strip().decode('utf-8'))

两种方法结果都没有ping的最后那三行
--- www.a.shifen.com ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4005ms
rtt min/avg/max/mdev = 3.923/5.201/6.448/1.001 ms

1. 想知道出现这种情况的原因.
2. 有什么方法能正确输出.

阅读 13.4k
1 个回答

因为满足 subprocess.Popen.poll(p) != None 后你只读了 p.stdout 的一行,但里面还有很多行。

例如把方法2最后一行的 p.stdout.readline() 改成 p.stdout.read() 即可。

推荐问题
宣传栏