Get Output On Screen from python script

Hi,

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 ?

Your question is not clear. I just checked your script and it seems to be working fine. Are you using Python 2.x or Python 3.x?

python --version

I’m using python 3.

My main script is running inside a django management command. I guess there’s something with the django integration because it does work fine when I put it out of django context.
I’ll let you know if I find something