[Tutor] Getting process output in real time

Jeff Shannon jeff@ccvcorp.com
Thu May 1 16:38:01 2003


Neil Hodge wrote:

> Jeff:
>
> Jeff Shannon wrote:
>
>> You may be able to use read() on your pipe object to, in essence, 
>> poll for new data.  Perhaps easiest would be to fire off your CLI 
>> program in a secondary thread, and use read(1) to grab individual 
>> bytes of output from it and then post those back to your main (GUI) 
>> thread.
>
>
> This sounds about right.  So, within the CLI thread, I am thinking 
> something like the following (more or less):
>
> [open pipe, etc.]
> while 1:
>     string = None
>     while 1:
>         c = read(fd, 1)
>         string = string + c
>     if c = os.linesep:
>             break
>     [assign string representing whole line to
>     trans-thread variable for action by other thread]
>     [check break condition for outer loop here]
> [close pipe]
>
> Seem reasonable? 


Well, for the "progress bar", the program probably puts everything on a 
single line, so buffering it line-by-line won't do you much good. 
 You'll probably want to send each byte to the GUI thread as it comes 
in.  (Btw, I strongly recommend using Queue.Queue for inter-thread 
communications.)  Something like

[open pipe]
while 1:
    c = fd.read(1)
    if c == [EOF]:
        break
    myqueue.put(c)
[close pipe]

should probably do the trick.  In your GUI thread, you can use an 
idle-handler or a timer to check the queue for contents.  I'd do all the 
assembling of characters in the main thread, since you mostly need to 
know when each character arrives.

Jeff Shannon
Technician/Programmer
Credit International