Re: dbm.open Blind?

Steven D. Majewski (sdm7g@elvis.med.virginia.edu)
Thu, 31 Mar 1994 02:13:12 -0500

#!/usr/local/bin/python

class File:
def __init__( self, fileobj ):
if hasattr( fileobj, '__methods__' ):
self._methods_ = fileobj.__methods__[:]
elif hasattr( fileobj, '_methods_' ):
self._methods_ = fileobj._methods_
else:
self._methods_ = dir(fileobj.__class__)
for m in self._methods_[:] :
if m[0] == '_' : self._methods_.remove(m)
self._fileobj = fileobj
for meth in self._methods_ :
setattr( self, meth, getattr( fileobj, meth ))

class Stream:
def __init__( self, nextmethod ):
self.nextmethod = nextmethod
self._buf = [ ]
def __len__( self ):
self._buf.append( self.nextmethod() )
if not self._buf[-1] :
del self._buf[-1]
return len( self._buf )
def __getitem__( self, i ):
if i >= len( self._buf ):
for j in range( len( self._buf ), i+1 ):
self._buf.append( self.nextmethod() )
return self._buf[i]
def __getslice__( self, i, j ):
junk = self.__getitem__( j )
return self._buf[i:j]

class Rfile( File ):
def __init__( self, fileobj ):
File.__init__( self, fileobj )
self._stream = Stream( self.readline )
self.readlines = self.stream
def stream( self ):
return self._stream

import sys

def test(f):
print 'Reading lines from ',f
for x in f.readlines(): print '<'+x[:-1]+'>'
print '<end.>'

if __name__ == '__main__' :
test( sys.stdin )
test( Rfile( sys.stdin ))

# - Steve M.
# ?