Get Output On Screen from python script




I’ve just read this article about capturing live output from python

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.

import subprocess
## command to run - tcp only ##
cmd = "python"
## 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 =
    if out == '' and p.poll() != None:
    if out != '':

An example of can be :

import time
for i in range(1, 40):

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