I want to run a Python script (or any executable, for that manner) from a python script and get the output in real time. I have followed many tutorials, and my current code looks like this:
import subprocess
with open("test2", "w") as f:
f.write("""import time
print('start')
time.sleep(5)
print('done')""")
process = subprocess.Popen(['python3', "test2"], stdout=subprocess.PIPE)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
print(output.strip())
rc = process.poll()
The first bit just creates the file that will be run, for clarity's sake.
I have two problems with this code:
It does not give the output in real time. It waits untill the process has finished.
It does not terminate the loop once the process has finished.
Any help would be very welcome.
EDIT: Thanks to @JohnAnderson for the fix to the first problem: replacing if output == '' and process.poll() is not None: with if output == b'' and process.poll() is not None:
outputfor something else? Because otherwise just leavingstdoutset toNoneshould work for you (still line buffered by default, may very depending on platform). Otherwise you needstdoutattached to a thread that consumes console output storing and printing content as it passes it through.outputlater on in the program.iftoif output == b'' and process.poll() is not None:otherwise it will never beTrue.-uto the python call created withsubprocessto turn buffering off (['python3', '-u', 'test2']) and you should see lines appear as they are "printed". Default behavior is: stdout to console -> line buffered, stdout to anything else -> default buffer (I reckon in your case 4KB).