Python-Nonblocking-subprocess

<pre>
import subprocess
import select
import os
import sys
import fcntl

p1 = subprocess.Popen("sleep 2 && echo done1 && sleep 5 && echo done2",
shell=True, stdout=subprocess.PIPE)
p2 = subprocess.Popen("sleep 3 && echo done3 && sleep 5 && echo done4",
shell=True, stdout=subprocess.PIPE)

pout = [p1.stdout.fileno(), p2.stdout.fileno()]
for fd in pout:
fl = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)

fd1_closed, fd2_closed = 0, 0
while not (fd1_closed and fd2_closed):
inputready, outputready, exceptready = select.select(pout, [], [])
for s in inputready:
got = os.read(s, 1)
if got:
print "got output %s from fd %d" % (got, s)
else:
if s == pout[0]:
fd1_closed = 1
elif s == pout[1]:
fd2_closed = 1
else:
pass
</pre>

output:
<pre>
<pre>
got output d from fd 3
got output o from fd 3
got output n from fd 3
got output e from fd 3
got output 1 from fd 3
got output
from fd 3
got output d from fd 4
got output o from fd 4
got output n from fd 4
got output e from fd 4
got output 3 from fd 4
got output
from fd 4
got output d from fd 3
got output o from fd 3
got output n from fd 3
got output e from fd 3
got output 2 from fd 3
got output
from fd 3
got output d from fd 4
got output o from fd 4
got output n from fd 4
got output e from fd 4
got output 4 from fd 4
got output
from fd 4
</pre>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,477评论 19 139
  • Python 在近年来的受欢迎程度剧增,部分原因在于该语言非常灵活,同时功能非常强大。Python 可用于系统管理...
    蝴蝶兰玫瑰阅读 3,567评论 0 0
  • 杯殇 小K稳了稳高瘦的身体,想往货架的深处躲去,可是背后都是和他同一批生产线出来的小伙伴,紧紧的一排挨着一排,根本...
    谕十猫阅读 3,427评论 2 1
  • 张家楼中心小学一心一意班 尹丁 和昔日相比,今天真是快乐的一天呀,寒假中都埋在作业堆里,而开学第一周周末作业非常少...
    见龙在田1阅读 3,051评论 0 0
  • 写卷首语的时候,我才想到大方已经编辑出版80期了,忽然间感慨万千,我做这个总编辑已经12年了。12年来...
    秦占勇阅读 1,729评论 2 3