Skip to content Skip to sidebar Skip to footer

Python: How To Read Stdout Of Subprocess In A Nonblocking Way

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.p

Solution 1:

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)

defreader(f,buffer):
   whileTrue:
     line=f.readline()
     if line:
        buffer.append(line)
     else:
        break

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

whileTrue:
  if linebuffer:
     print linebuffer.pop(0)
  else:
     print"nothing here"
     time.sleep(1)

Solution 2:

You could try this:

import subprocess
import os

""" Continuously print command output """""" Will only work if there are newline characters in the output. """defrun_cmd(command):    
    popen = subprocess.Popen(command, stdout=subprocess.PIPE)
    returniter(popen.stdout.readline, b"")

for line in run_cmd([path_to_exe, os.path.join(temp_dir,temp_file)]):
    print(line), # the comma keeps python from adding an empty line

Post a Comment for "Python: How To Read Stdout Of Subprocess In A Nonblocking Way"