I'm writing a program for Windows 7 using Python 2.7.9. This program allows the user to schedule and run a list of scripts and needs to show the output of the scripts in real-time. In order to run the scripts I have the following code:
self.proc = Popen(command, shell=False, stdout=PIPE, stderr=STDOUT)
for line in iter(self.proc.stdout.readline, b''):
print line
This is working and runs the scripts just fine but the issue is that I only see output after the script has finished running which is not acceptable. For example I have a simple program:
from time import sleep
print "test: Can you see me?"
#sys.stdout.flush()
sleep(10)
print "ending"
I do not see any of the print statements until after the sleep time at which point the script ends and everything is printed to the console at once. I've tried a few different approaches but nothing gets it to print in real time. The only thing I have found to work is to make the script I'm running unbuffered by adding the sys.stdout.flush() or adding the following to the beginning of each python script I want to run:
unbuffered = os.fdopen(sys.stdout.fileno(), 'w', 0)
sys.stdout = unbuffered
I also need to be able to run other scripts like perl and java so this is not a good fix.
So is there any way to execute scripts from a python program and have the output shown in real time? I'm open to other suggestions as well, maybe there is a better approach than using subprocess that I'm not aware of.