Following a file, or cloning tail

Gordon McMillan gmcm at hypernet.com
Thu Jun 29 16:44:54 EDT 2000


Boudewijn Rempt wrote: 

>On Wed, 28 Jun 2000, Darrell Gallion wrote:
>
>> If your on Windows and can wait for the file to complete writing,
>> check out http://www.dorb.com/darrell/win32WorkSvr/
>> 
>
>I have to be portable, worse luck!
>
>> The best solution might be to use popen if you can.
>
>You mean simply a os.popen("tail -f myfile","r").readline() should
>work? It sounds to easy to be true ;-)

Um, you said you had to be portable. Not only is tail not standard on 
Windows, but os.popen is flaky there too (depending on circumstances too 
painful to enumerate).

However, tail (usually - some implementations differ) does almost what the 
following code does. Note that even this isn't portable, because Windows 
doesn't have ino's to check. I have the code this is extracted from 7x24 
for years on my Linux box. I call checkino about once every 5 minutes.

import os, stat, string

class Tailer:

    def __init__(self, fnm):

        self.fnm = fnm

        self.ino = None

        self.f = None

        self.checkino()

        
    def checkino(self):        
        st = os.stat(self.fnm)

        ino = st[stat.ST_INO]

        if ino <> self.ino:

            if self.f:

                self.f.close()

            self.f = open(self.fnm,'r',0)

            if self.ino is None:

                self.pos = st[stat.ST_SIZE]

            else:

                self.pos = 0

            self.f.seek(self.pos)

            self.ino = ino

            self. buff = ''

            
    def check(self):
        self.f.seek(0)

        self.f.seek(self.pos)

        self.buff = self.buff + self.f.read()

        self.pos = self.f.tell()

        lines = string.split(self.buff, '\n')

        self.buff = lines[-1]

        return lines[:-1]

        
    def close(self):

        self.f.close()

        self.f = None

        self.ino = None


- Gordon



More information about the Python-list mailing list