Greetings,
I am using Python 2.6 on Ubuntu. I have a problem with simultaneously
reading lines from stdout of a subprocess.

listargs.c:
#include <stdio.h>
#include <unistd.h>
int main (int argc, char ** argv) {
        int i;
        // while (1)
        for (i=0; i<argc; i++) {
                puts (argv[i]);
                fflush (stdout);
                sleep(1);
        }
}
This is a (sample) non-terminating process with occasional continous
standard output; could have been a file scanner, etc.
./listargs 1 2 3
./listargs qwe 123 qwr qwt | grep --line-buffered qw
works as expected.

This is my python program. The whole output of the subprocess is
displayed all at once, after the sum of all delays; I want to have
real-time output like above. You can run it with an argument as well
to use the terminal as output. I have tried bufsize=-1,0,1,999 and
shell=True,False but none worked.
subproc.py:
from subprocess import Popen, PIPE, STDOUT
from threading import Thread
import gtk
import sys

class MyThr (Thread):
        def __init__ (self, tb):
                Thread.__init__ (self)
                self.tb = tb
                self.sp = None

        def run (self):
                self.sp = Popen(['./listargs', 'a', 'bc', '1234'], bufsize=-1,
stdout=PIPE)
                for l in self.sp.stdout:
                        if len(sys.argv)>1:
                                print 'O', l, # this shows that I do get 
line-by-line output, just
not real-time
                                sys.stdout.flush()
                        else:
                                # self.tb.get_buffer().insert_at_cursor (l)
                                self.tb.get_buffer().set_text (l)
                                self.tb.show()
                                gtk.main_iteration (False)

if len(sys.argv)>1:
        t = MyThr (None)
        t.start()
else:
        dlg = gtk.Dialog ('Dummy Dialog', buttons=(gtk.STOCK_CLOSE,
gtk.RESPONSE_CLOSE))
        dlg.vbox.pack_start (gtk.Label ('Dummy Dialog running..'), False,
False, 4)
        tb = gtk.TextView()
        tb.set_editable (False)
        dlg.vbox.pack_start (tb)
        dlg.set_default_size (400, 250)
        dlg.show_all()
        t = MyThr (tb)
        t.start()
        dlg.run()

t.join()
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to