2014-07-17 77 views

回答

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)