[Python-Dev] an idea for improving struct.unpack api
Gustavo J. A. M. Carneiro
gjc at inescporto.pt
Thu Jan 6 16:21:36 CET 2005
On Thu, 2005-01-06 at 13:17 +0000, Michael Hudson wrote:
> Ilya Sandler <ilya at bluefir.net> writes:
>
> > A problem:
> >
> > The current struct.unpack api works well for unpacking C-structures where
> > everything is usually unpacked at once, but it
> > becomes inconvenient when unpacking binary files where things
> > often have to be unpacked field by field. Then one has to keep track
> > of offsets, slice the strings,call struct.calcsize(), etc...
>
> IMO (and E), struct.unpack is the primitive atop which something more
> sensible is built. I've certainly tried to build that more sensible
> thing at least once, but haven't ever got the point of believing what
> I had would be applicable to the general case... maybe it's time to
> write such a thing for the standard library.
I've been using this simple wrapper:
def stream_unpack(stream, format):
return struct.unpack(format, stream.read(struct.calcsize(format)))
It works with file-like objects, such as file, StringIO,
socket.makefile(), etc. Working with streams is useful because
sometimes you don't know how much you need to read to decode a message
in advance.
Regards.
>
> Cheers,
> mwh
>
--
Gustavo J. A. M. Carneiro
<gjc at inescporto.pt> <gustavo at users.sourceforge.net>
The universe is always one step beyond logic.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: smime.p7s
Type: application/x-pkcs7-signature
Size: 3086 bytes
Desc: not available
Url : http://mail.python.org/pipermail/python-dev/attachments/20050106/349cb526/smime.bin
More information about the Python-Dev
mailing list