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. 有什么方法能正确输出.

阅读 14.3k
1 个回答

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

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

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏