免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2720 | 回复: 2
打印 上一主题 下一主题

为什么subprocess.Popen.poll()=0,但是pipe里面还有没读完的数据 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2012-10-18 14:59 |只看该作者 |倒序浏览
可能标题写的有点不清楚,具体情况如下:
写一个程序,能获得程序输出,并且在程序执行完毕之后,能获知。程序如下
  1. import subprocess

  2. pp = subprocess.Popen('ping -c4 www.google.cn', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  3. while 1:
  4.         line = pp.stdout.readline()
  5.         print('out-->'+line+'<')
  6.         if subprocess.Popen.poll(pp)==0:
  7.                 break

  8. print('DONE')
复制代码
实际执行的效果有2种情况
第一种
out-->PING www.google.cn (203.208.45.212) 56(84) bytes of data.<
out-->64 bytes from 203.208.45.212: icmp_seq=1 ttl=55 time=4.03 ms<
out-->64 bytes from 203.208.45.212: icmp_seq=2 ttl=55 time=3.18 ms<
out-->64 bytes from 203.208.45.212: icmp_seq=3 ttl=55 time=3.90 ms<
out-->64 bytes from 203.208.45.212: icmp_seq=4 ttl=55 time=4.47 ms<
DONE

---------------------------
第二种

out-->PING www.google.cn (203.208.46.212) 56(84) bytes of data.<
out-->64 bytes from 203.208.46.212: icmp_seq=1 ttl=54 time=26.3 ms<
out-->64 bytes from 203.208.46.212: icmp_seq=2 ttl=54 time=3.22 ms<
out-->64 bytes from 203.208.46.212: icmp_seq=3 ttl=54 time=6.95 ms<
out-->64 bytes from 203.208.46.212: icmp_seq=4 ttl=54 time=4.59 ms<
out--><
out-->--- www.google.cn ping statistics ---<
out-->4 packets transmitted, 4 received, 0% packet loss, time 3009ms<
out-->rtt min/avg/max/mdev = 3.225/10.282/26.363/9.380 ms<
out--><
out--><
out--><
out--><
DONE

第一种执行结果占多数,第二种执行结果,有时候会出现。

按照实际执行ping -c4 www.google.cn的情况看,第一种情况少了最后的三行,所以说是不正确的。但是为什么常常是这种情况哪?求版主和各位大大帮忙看看那问题。

论坛徽章:
0
2 [报告]
发表于 2013-04-25 04:38 |只看该作者
  1. while 1:
  2.         line = pp.stdout.readline()
  3.         if not line:
  4.                break
  5.         print('out-->'+line+'<')
复制代码
回复 1# spyman1802


   

论坛徽章:
0
3 [报告]
发表于 2013-04-25 20:41 |只看该作者
很显然,第一种情况表明网速快,命令已经结束了,pipe里的data还没有读完。如果网速够慢的话的,那么正好是命令执行完的时候,pipe里的data正好读完。
我帮你改进了一下:
  1. import subprocess

  2. pp = subprocess.Popen('ping www.google.cn', shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
  3. while 1:
  4.     line = pp.stdout.readline()
  5.     if line:                                             # 避免出现空行
  6.         print('out-->'+line.strip()+'<')
  7.     if subprocess.Popen.poll(pp) == 0 and not line:      # 确保命令已经正确退出且pipe里data已经读完。
  8.         break
  9. print('DONE')
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP