Python:如何以非阻塞方式读取子进程的stdout

sta*_*nko 5 python standards subprocess output

我试图创建一个简单的python脚本,启动子进程并监视其标准输出.以下是代码中的代码段:

process = subprocess.Popen([path_to_exe, os.path.join(temp_dir,temp_file)], stdout=subprocess.PIPE)
while True:   
    output=process.stdout.readline()
    print "test"
Run Code Online (Sandbox Code Playgroud)

问题是脚本挂起output=process.stdout.readline()并且该行print "test"仅在子进程终止后执行.

有没有办法读取标准输出并打印它,而不必等待子进程终止?

我开始的子进程是Windows二进制文件,我没有源代码.

我发现了几个类似的问题,但答案只适用于Linux或者我有启动的suprocess的来源.

xva*_*van 7

检查选择模块

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)
Run Code Online (Sandbox Code Playgroud)

编辑:

非posix系统的螺纹解决方案:

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)
Run Code Online (Sandbox Code Playgroud)