Unbuffered keyboard input

Jake Speed speed at ?.com
Tue Nov 7 12:01:25 EST 2000


apighin at my-deja.com wrote in <8u99fl$jch$1 at nnrp1.deja.com>:

>To tell the truth, what I am really trying to do is to parse a file
>that is ever expanding.  The file will be open()ed, parsed, but will
>continue to grow in the background.  I can not seem to get Python to
>see that the file have changed and begin processing again.  Ideas?

This is the what the Unix command 'tail -f' does.  When you get an
end-of-file, any further read will immediately return.  You need
to wait a bit, then clear the EOF status with a seek() and see
if there is more data. 
 
import time

f = open("data.txt", "rb")

while 1:
        data = f.read(1024)
        if data:
                print repr(data)
        else:
                time.sleep(1)   # wait a second
                f.seek(0, 1)    # seek to the current position

f.close()
 
     
Note that the loop never exits, because there's no way to tell 
when the writing process has closed!  If you were reading a pipe,
socket, or terminal, which stdin usually is, read() would block
until more data was available, and would only return EOF when
the writing process closed its end.

-Speed!




More information about the Python-list mailing list