Python' s struct.unpack
返回一个元组。有没有办法在不构造中间元组的情况下逐个产生元素?
答案 0 :(得分:1)
不是真的。您可以使用ctypes.Structure
在访问它们时懒洋洋地创建Python对象。否则你需要自己写点东西。如下所示:
import struct
import re
re_split_fmt = re.compile("\s*[0-9]*\S", re.DOTALL)
def unpack_iter(fmt, buf):
if fmt == "":
return ()
if fmt[0] in "<>=!":
byteorder = fmt[0]
fmt = fmt[1:]
else:
raise ValueError, "can't handle possibly padded formats"
if "p" in fmt:
raise ValueError, "can't handle pascal strings"
def generator(i, buf, offset = 0):
for m in i:
fmt = byteorder + m.group(0)
size = struct.calcsize(fmt)
if fmt[-1] != 'x':
s = buf[offset : offset + size]
for a in struct.unpack(fmt, s):
yield a
offset += size
return generator(re_split_fmt.finditer(fmt), buf)