reading lines from non-terminating subprocess; threading, gtk

J

jfcg

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,955
Messages
2,570,117
Members
46,705
Latest member
v_darius

Latest Threads

Top