YAS to the "Reading line-by-line" Problem
Jesse D. Sightler
jsight at mindspring.com
Tue Jun 22 15:09:36 EDT 1999
Ack is raising an exception for a normally occuring event really a
_good_ idea? Generally exceptions are only used for things that
actually are error conditions, and it would seem to me that using them
as nothing more than a fancy flow-control construct is a sure path to
nasty spaghetti code.
I really do not like this idea. :)
Moshe Zadka wrote:
>
> (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.
--
---------------
Jesse D. Sightler
http://www3.pair.com/jsight/
"Do not use a hatchet to remove a fly from your friend's forehead."
- Chinese Proverb
More information about the Python-list
mailing list