切片是个好方法,但是它一次只能取得一个字段;如果还考虑字段的长度,struct.unpack可能更适合。
import struct
def fields(baseformat, theline, lastfield=False):
# theline超出的长度也由这个base-format确定
# (通过struct.calcsize计算确切的长度)
numremain = len(theline) - struct.calcsize(baseformat)
# 用合适的s或x字段完成格式,然后unpack
format = "%s %d%s" % (baseformat, numremain, lastfield and "s" or "x")
return struct.unpack(format, theline)
利用缓存的方法:
import struct
def fields(baseformat, theline, lastfield=False, _cache={}):
# 生成键并尝试获得缓存的格式字符串
key = baseformat, len(theline), lastfield
format = _cache.get(key)
if format is None:
# 没有缓存的格式字符串,创建并缓存之
numremain = len(theline) - struct.calcsize(baseformat)
_cache[key] = format = "%s %d%s" % (baseformat, numremain, lastfield and "s" or "x")
return struct.unpack(format, theline)