[Tutor] tail -f
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Tue, 26 Mar 2002 20:13:38 -0800 (PST)
> So basically, they open the file, and just stare at it's size, forever (or
> until the user gets tired). Whenever the file size changes, it just
> prints the remainder out to screen. They do something like a time.sleep()
> to make the busy waiting look less bad. *grin* By default, they poll
> every 1 second:
>
> /***/
> static unsigned int sleep_interval = 1;
> /***/
Here's an example of how we might do it in Python:
###
#!/usr/local/bin/python
"""A demonstration of file following.
Danny Yoo (dyoo@hkn.eecs.berkeley.edu)
"""
import os.path, time, sys
DELAY=1
def follow(filename):
f = open(filename)
size = 0
while 1:
new_size = os.path.getsize(filename)
if new_size > size:
f.seek(size)
sys.stdout.write(f.read())
elif new_size < size:
print "=== File truncation ==="
size = new_size
time.sleep(DELAY)
if __name__ == '__main__':
if len(sys.argv) != 2:
print "We need a file!"
else:
follow(sys.argv[1])
###
Hope this helps!