I am using a colleague's code that handles network stream information using struct.unpack and I was wondering if someone can give me an explanation of what the following code does:
def unpack_from(self, fmt, data, offset = 0):
(byte_order, fmt, args) = (fmt[0], fmt[1:], ()) if fmt and fmt[0] in ('@', '=', '<', '>', '!') else (
'@', fmt, ())
fmt = filter(None, re.sub("p", "p", fmt).split(''))
for sub_fmt in fmt:
if sub_fmt == 'p':
(str_len,) = struct.unpack_from('B', data, offset)
sub_fmt = str(str_len + 1) + 'p'
sub_size = str_len + 1
else:
sub_fmt = byte_order + sub_fmt
sub_size = struct.calcsize(sub_fmt)
args += struct.unpack_from(sub_fmt, data, offset)
offset += sub_size
return args
Since I am new in Python and have never used the struct library I have no idea what is happening in this piece of code. Appreciate the help!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…