I’ve just read this article about capturing live output from python https://www.cyberciti.biz/faq/python-run-external-command-and-get-output/
I’m creating a tool in python that calls external commands from third party libraries and I’m trying to get the output of an external python command.
#!/usr/bin/python import subprocess ## command to run - tcp only ## cmd = "python anylongrunning_script.py" ## run it ## p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE) ## But do not wait till netstat finish, start displaying output immediately ## while True: out = p.stderr.read(1) if out == '' and p.poll() != None: break if out != '': sys.stdout.write(out) sys.stdout.flush()
An example of anylongrunning_script.py can be :
import time for i in range(1, 40): print(i) time.sleep(0.5)
Nothing appears live, all the output is sent at the end of the script.
I see a difference between capturing a shell “echo” and a python “print”. Is this normal ?