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)
Related posts
- How to use the bash shell with Python's subprocess module instead of /bin/sh — posted 2011-04-13
- How to get stdout and stderr using Python's subprocess module — posted 2008-09-23
- How to use python and popen4 to capture stdout and stderr from a command — posted 2007-03-12
Comments
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.
Hello.
after a huge googling, i found your solution and i want to appreciate your blog.
Thank you very muchhhhhhhhhhhhh
hi guys i couldnt capture iftop output stream from the above code pls help i get two lines and waiting for ever
Heey this helped me a lot, I didn't use the exact implementaion but give a good idea Cheers
Doesn't work. Blocks on readline( ).
disqus:2279800256
Better yet, use a thread to listen for output:
http://stackoverflow.com/qu...
disqus:2654375223