SaltyCrane Blog — Notes on JavaScript and web development

How to capture stdout in real-time with Python

This solution is thanks to this article.

import subprocess

def myrun(cmd):
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout = []
    while True:
        line = p.stdout.readline()
        print line,
        if line == '' and p.poll() != None:
    return ''.join(stdout)


#1 Paul commented on :

I know you posted this two years ago, but just wanted to say THANKS. 2 hours of hunting for a solution on various dicussion board getting vauge answers...

This hit the nail on the head for my problem.

#2 Meysam commented on :


after a huge googling, i found your solution and i want to appreciate your blog.

Thank you very muchhhhhhhhhhhhh

#3 keith commented on :

hi guys i couldnt capture iftop output stream from the above code pls help i get two lines and waiting for ever

#4 noahfx commented on :

Heey this helped me a lot, I didn't use the exact implementaion but give a good idea Cheers

#5 Jon Wong commented on :

Doesn't work. Blocks on readline( ).