python stdout.read()阻塞,Python:如何以非阻塞方式读取子流程的stdout

I am trying to make a simple python script that starts a subprocess and monitors its standard output. Here is a snippet from the code:

process = subprocess.Popen([path_to_exe, os.path.join(temp_dir,temp_file)], stdout=subprocess.PIPE)

while True:

output=process.stdout.readline()

print "test"

The problem is that the script hangs on output=process.stdout.readline() and that the line print "test" only executes after the subprocess is terminated.

Is there a way to read standard output and print it without having to wait for the subprocess to terminate?

The subprocess which I am starting is a Windows binary for which I do not have the source code.

I have found several similar questions, but the answers are only applicable on Linux or in case I have the source of the suprocess I am starting.

解决方案

Check select module

import subprocess

import select

import time

x=subprocess.Popen(['/bin/bash','-c',"while true; do sleep 5; echo yes; done"],stdout=subprocess.PIPE)

y=select.poll()

y.register(x.stdout,select.POLLIN)

while True:

if y.poll(1):

print x.stdout.readline()

else:

print "nothing here"

time.sleep(1)

EDIT:

Threaded Solution for non posix systems:

import subprocess

from threading import Thread

import time

linebuffer=[]

x=subprocess.Popen(['/bin/bash','-c',"while true; do sleep 5; echo yes; done"],stdout=subprocess.PIPE)

def reader(f,buffer):

while True:

line=f.readline()

if line:

buffer.append(line)

else:

break

t=Thread(target=reader,args=(x.stdout,linebuffer))

t.daemon=True

t.start()

while True:

if linebuffer:

print linebuffer.pop(0)

else:

print "nothing here"

time.sleep(1)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值