Created
December 7, 2011 08:00
-
-
Save geekman/1441933 to your computer and use it in GitHub Desktop.
unpack struct from stream-like object
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# | |
# example: | |
# f = open('/path/some/file', 'r') | |
# age, year, c = unpack('>HHB', f) | |
# | |
import struct | |
def unpack(fmt, f, offset=None): | |
"""Unpacks data read from file stream at optionally specified offset""" | |
isStruct = isinstance(fmt, struct.Struct) | |
size = fmt.size if isStruct else struct.calcsize(fmt) | |
pos = f.tell() | |
if offset is not None: f.seek(offset) | |
s = f.read(size) | |
if len(s) < size: | |
raise ValueError, "cannot unpack %s - not enough bytes read" % fmt | |
if offset is not None: f.seek(pos) | |
return fmt.unpack(s) if isStruct else struct.unpack(fmt, s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment