I want to start a program which needs several minutes to complete. During this time I want to read the progress message of the program (which are printed on the stdout). The pro
Simplest is to call Popen with the keyword argument stdout=subprocess.PIPE
.
p = subprocess.Popen(["ls"], stdout=subprocess.PIPE)
while True:
line = p.stdout.readline()
if not line:
break
print line
To see this in action, here are two sample scripts. Make them both in the same directory and run python superprint.py
printandwait.py:
import time
import sys
print 10
sys.stdout.flush()
time.sleep(10)
print 20
sys.stdout.flush()
superprint.py:
import subprocess
import sys
p = subprocess.Popen(["python printandwait.py"], shell=True, stdout=subprocess.PIPE)
while True:
print "Looping"
line = p.stdout.readline()
if not line:
break
print line.strip()
sys.stdout.flush()