[Tutor] capture output from a subprocess while it is being produced

Alan Gauld alan.gauld at yahoo.co.uk
Tue Jun 14 19:49:50 EDT 2016


On 14/06/16 21:03, Albert-Jan Roskam wrote:

> from subprocess import Popen, PIPE
> from threading import Thread
> from collections import deque
> import sys
> import time
> import os.path
> 
> 
> def process(dq):
>     """Run a commandline program, with lots of output"""
>     cwd = os.path.dirname(sys.executable)
>     proc = Popen("ls -lF", cwd=cwd, shell=True, stdout=PIPE, stderr=PIPE)  
>     #print len(proc.stdout.readlines())  # 2964
>     output = errors = None
>     while True:
>         try:
>             #output, errors = proc.communicate() # "Wait for process to terminate."  
>             output = proc.stdout.read()  # docs: "Use communicate() rather than .stdin.write, .stdout.read or .stderr.read"

read() reads the entire "file", try using readline() instead.


-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list