Imitating "tail -f"

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Sat Nov 21 23:10:02 EST 2009


On 02:43 am, ivoras at gmail.com wrote:
>I'm trying to simply imitate what "tail -f" does, i.e. read a file, 
>wait
>until it's appended to and process the new data, but apparently I'm
>missing something.
>
>The code is:
>
>54     f = file(filename, "r", 1)
>55     f.seek(-1000, os.SEEK_END)
>56     ff = fcntl.fcntl(f.fileno(), fcntl.F_GETFL)
>57     fcntl.fcntl(f.fileno(), fcntl.F_SETFL, ff | os.O_NONBLOCK)
>58
>59     pe = select.poll()
>60     pe.register(f)
>61     while True:
>62         print repr(f.read())
>63         print pe.poll(1000)
>
>The problem is: poll() always returns that the fd is ready (without
>waiting), but read() always returns an empty string. Actually, it
>doesn't matter if I turn O_NDELAY on or off. select() does the same.
>
>Any advice?

select(), poll(), epoll, etc. all have the problem where they don't 
support files (in the thing-on-a-filesystem sense) at all.  They just 
indicate the descriptor is readable or writeable all the time, 
regardless.

"tail -f" is implemented by sleeping a little bit and then reading to 
see if there's anything new.

Jean-Paul



More information about the Python-list mailing list