EOFError why print(e) cannot print out any information ?

Peter Otten __peter__ at web.de
Wed Dec 26 13:21:18 CET 2012


iMath wrote:

> f = open('UsersInfo.bin','rb')
> while True:
>         try:
>                 usrobj = pickle.load(f)
>         except EOFError as e:
>                 print(e)
>                 break
>         else:
>                 usrobj.dispuser()
> f.close()
 
> why print(e) cannot print out any information ?

Because the relevant code in pickle doesn't supply an error message; it's 
just

raise EOFError

While you can add the information yourself by subclassing the Unpickler...

class MyUnpickler(pickle.Unpickler):
    def __init__(self, file, **kw):
        super().__init__(file, **kw)
        self.file = file
    def load(self):
        try:
            return super().load()
        except EOFError:
            raise EOFError("EOFError: Reached end of {}".format(self.file))

with open('UsersInfo.bin','rb') as f:
    load = MyUnpickler(f).load
    while True:
        try:
            usrobj = load()
        except EOFError as e:
            print(e)
            break
        else:
            usrobj.display()

... it might be a good idea to make a feature request on 
<http://bugs.python.org>.




More information about the Python-list mailing list