Graceful detection of EOF

Jeff Epler jepler at unpythonic.net
Thu Oct 7 21:37:59 CEST 2004


Write a file-like object that can "look ahead" and provide a flag to
check in your unpickling loop, and which implements enough of the file
protocol ("read" and "readline", apparently) to please pickle.  The
following worked for me.

class PeekyFile:
    def __init__(self, f):
        self.f = f
        self.peek = ""

    def eofnext(self):
        if self.peek: return False
        try:
            self.peek = self.f.read(1)
        except EOFError:
            return True
        return not self.peek

    def read(self, n=None):
        if n is not None:
            n = n - len(self.peek)
            result = self.peek + self.f.read(n)
        else:
            result = self.peek + self.f.read()
        self.peek = ""
        return result

    def readline(self):
        result = self.peek + self.f.readline()
        self.peek = ""
        return result

import StringIO, pickle
o = StringIO.StringIO()
for x in range(5):
    pickle.dump(x, o)
i = PeekyFile(StringIO.StringIO(o.getvalue()))
while 1:
    i.eofnext()
    if i.eofnext():
        break
    print pickle.load(i)
print "at the end"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 196 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20041007/29cf3bd0/attachment.sig>


More information about the Python-list mailing list