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):
    """from http://blog.kagesenshi.org/2008/02/teeing-python-subprocesspopen-output.html
    """
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout = []
    while True:
        line = p.stdout.readline()
        stdout.append(line)
        print line,
        if line == '' and p.poll() != None:
            break
    return ''.join(stdout)

Comments


#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 :

Hello.

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( ).

disqus:2279800256