[pygtk] Asynchronous access at output of os.popen() call

A.T.Hofkamp a.t.hofkamp at tue.nl
Wed Aug 20 17:39:43 WST 2008


togix wrote:

> eg. imagine that I want to call a simple program "work.exe" that prints out
> some line, waiting some seconds in between:
> 
> [code]
> /* Program work.c */
> int main (int argc, char *argv[])
> {
>       int i = 0;
>       for (i=0; i<4; i++)
>       {
>             printf("Working... %d\n", i);
>             sleep(5);
>       }
>       printf("END");
>       return(0);
> }
> [/code]

Force the printed text from the program output buffer into the OS by using 
fflush(), by outputting more information, or by setting the flushing policy or 
buffer size of stdout.

Linux (most Unixes in fact) switches to block transfers of several kilo-bytes 
when not communicating to a terminal but to a pipe (ie './program | cat'). 
First step is to force the printed text out of the program.

> 
> And then call it from the Python interface:
> 
> [code]
> ...
> textview = gtk.TextView()
> textbuffer = textview.get_buffer()
> 
> cmd = "./work.exe"
> for line in os.popen(cmd):
>       textbuffer.insert_at_cursor(line)
>       while gtk.events_pending():
>             gtk.main_iteration(False)
> ...
> [/code]

You can also attach a file handle to an event handler using 
gobject.io_add_watch() and get a call-back when there is data.

Albert



More information about the pygtk mailing list