2012-10-01 52 views
3

嗯,我有两个脚本。如下打印出b.py脚本输出的a.py:Popen stdout读取管道,使用睡眠死锁

#a.py 
from subprocess import Popen, PIPE, STDOUT 

p = Popen(['/Users/damian/Desktop/b.py'], shell=False, stdout=PIPE, stderr=STDOUT) 

while p.poll() is None: 
    print p.stdout.readline() 


#b.py 
#!/usr/bin/env python 
import time 

while 1: 
    print 'some output' 
    #time.sleep(1) 

这works.But, 为什么我的脚本僵局,当我取消对time.sleep()行?

+0

如果分开执行,你确定b.py不会自己死锁吗? (检查缩进,如果它们对于两条线都是相同的,则为1:! –

回答

5

您的输出可能被缓冲。添加.flush()标准输出将其清除:

import sys 
import time 

while 1: 
    print 'someoutput' 
    sys.stdout.flush() 
    time.sleep(1) 
+0

事实上,flush是这样做的,谢谢 – ScotchAndSoda

2

如果您在a.py添加-u到呼叫(使输出缓冲),那么你并不需要修改b.py脚本:

import sys 
from subprocess import Popen, PIPE, STDOUT 

p = Popen([sys.executable, '-u', '/Users/damian/Desktop/b.py'], 
      stdout=PIPE, stderr=STDOUT, close_fds=True) 
for line in iter(p.stdout.readline, ''): 
    print line, 
p.stdout.close() 
if p.wait() != 0: 
    raise RuntimeError("%r failed, exit status: %d" % (cmd, p.returncode)) 

more ways to get output from a subprocess

+0

很好,呵呵,还要感谢输出的例子,再次证明了Python的强大功能。 – ScotchAndSoda