1

Being a Python noob I need to run a third party application (which writes its stdout into single line, they probably use something like skip_eol=True), from within my python script and display the app's stdout live.

This

process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
for line in iter(process.stdout.readline, b''):
    print line.rstrip()

only allows me to get the stdout once the child process completed. I don't clearly understand how do I catch the entire stdout?

hdf
  • 155
  • 3
  • 11

1 Answers1

0

Try like that:

#!/usr/bin/env python2

import subprocess
import shlex

process = subprocess.Popen(shlex.split('./bash_1_line_per_second.sh'), stdout=subprocess.PIPE)

while process.poll() is None:
    print 'reading' # Just to understand better what is happening
    print process.stdout.read(1)

This reads one character at time... is the output of cmd binary? In that case this probably wont work...

If you provide the output of cmd I can be more precise! In particular, if you need help to rebuild the line from the single characters.

This is the bash script I used to test:

#!/bin/bash

counter=0
while [[ "a" == "a" ]]; do
  echo -n "This is the line number $counter"
  let counter+=1
  sleep 1
  if [[ $counter -eq 5 ]]; then 
      exit 0
  fi
done
Riccardo Petraglia
  • 1,943
  • 1
  • 13
  • 25