YAS to the "Reading line-by-line" Problem

Moshe Zadka moshez at math.huji.ac.il
Tue Jun 22 17:37:06 CEST 1999


(YAS == Yet Another Solution)

This solution introduces file-like objects which do the Right Thing(TM) at
EOF: raise EOFError (instead of returning an empty string)

----------------- cut here ------------------
class File:
        '''\
        File-like objects which throw EOFError on End-of-File.

        Initialize with a file-like object.
        '''
        def __init__(self, file):
                self.__file=file

        def __getattr__(self, name):
                if name[:4]!='read':
                        return getattr(self.__file, name)
                return _Wrap(getattr(self.__file, name))

class _Wrap:
        def __init__(self, function):
                self.function=function

        def __call__(self, *args, **kw):
                ret=apply(self.function, args, kw)
                if ret=='': raise EOFError, 'no more data in file'
                return ret

def open(file, mode='r'):
        '''\
        return a file like object open to /file/ with mode /mode/,
        which throws an EOFError on EOF
        '''
        import __builtin__
        return File(__builtin__.open(file, mode))

def _test():
        import sys
        file=open('/etc/passwd')
        try:
                while 1:
                        sys.stdout.write(file.readline())
        except EOFError: pass

if __name__=='__main__':
        _test()
---------------------------- cut here ---------------------------

--
Moshe Zadka <mzadka at geocities.com>. 
#!/usr/bin/tail -1
Just another tail hacker.





More information about the Python-list mailing list