0

Here is my script:

def tail(file, delay=0.5):
    f = open(file, 'r')
    f.seek(0, 2)
    while True:    
        line = f.readline()
        print 'line: ' + line
        if not line:
            time.sleep(delay)
        else:
            print 'line found!'

When i open the file and add some lines to it, this script is not picking it up. I am doing this on linux.

wkl
  • 77,184
  • 16
  • 165
  • 176
  • 1
    Your example code works for me. How are you writing to the file? – David Z Oct 28 '11 at 15:34
  • i am opening it in vi and adding some lines to it and then writing it. – lee_connell Oct 28 '11 at 16:07
  • That's odd... I did the same thing and it still works for me. I'm not sure what to tell you. (For testing the Python code itself, I would use `echo linetexthere >> file` instead of an editor like vi) – David Z Oct 28 '11 at 16:21
  • related: http://stackoverflow.com/questions/182197/how-do-i-watch-a-file-for-changes-using-python http://stackoverflow.com/questions/136168/get-last-n-lines-of-a-file-with-python-similar-to-tail – jfs Oct 28 '11 at 16:25
  • David, thanks for input, the problem was adding a line to the file with vi. That did not work, however appending some text via echo did work. Thanks everyone! – lee_connell Oct 28 '11 at 17:48

2 Answers2

1

use open('filename', 'a') instead of open('filename', 'r') for adding lines to the file ... I think you actually want to append to the file rather than reading it.

musefan
  • 47,875
  • 21
  • 135
  • 185
Rites
  • 11
  • 1
0

The code looks fine so there is likely a buffering issue. Try using f.read(100) instead of readline so that you read whatever is available rather than searching for line endings.

Raymond Hettinger
  • 216,523
  • 63
  • 388
  • 485
  • I did that and still do not get anything. Is this because the file is buffered in memory so it won't detect changes on disk? – lee_connell Oct 28 '11 at 16:05