Popen stdout读取管道,死锁使用睡眠

2024-09-29 04:29:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个剧本。a.py,它打印b.py脚本的输出,如下所示:

#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)

这个很好。但是, 为什么在取消注释时脚本会死锁时间。睡觉()行?在


Tags: frompyimport脚本timestdoutuserssubprocess
2条回答

你的输出可能是缓冲的。为stdout添加一个.flush()以清除它:

import sys
import time

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

如果将-u添加到a.py中的调用(使输出无缓冲),则无需修改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。在

相关问题 更多 >