I am trying to get a real time output from a bash command so i can play with the data easier.
In this code, the command iostat 1
works fine and prints output at 1 second. The command sar -u 1 20
, which runs as expected on the command line (printing 1 line every second up to 20), waits until the command is complete ~20 seconds, before printing each line with a .1 second delay.
I am planning on running these commands indefinitely, and need this part to work. Any thoughts on whats wrong? I am on OSX.
import subprocess
import time
# run a command and constantly check for new output, if you find it, print it and continue
# if the command is done, break out
try:
command="sar -u 1 20"
process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
while True:
time.sleep(.1) # so i don't kill the cpu on the machine i'm checking
output = process.stdout.readline()
#if process.poll() is not None:
# break
if output:
print output.strip()
except KeyboardInterrupt:
print 'Exiting...'
return_code = process.poll()
print return_code