Struct.unpack_from方法代码示例

256 阅读10分钟

本文整理汇总了Python中struct.Struct.unpack_from*方法*的典型用法代码示例。如果您正苦于以下问题:Python Struct.unpack_from方法的具体用法?Python Struct.unpack_from怎么用?Python Struct.unpack_from使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在struct.Struct的用法示例。

在下文中一共展示了Struct.unpack_from方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: read

▲ 点赞 9 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
    def read(self, raw, offset):
        self.data = dict()

        self.data["terrain_border"] = list()
        for i in range(16):
            t = TerrainBorder()
            offset = t.read(raw, offset)
            self.data["terrain_border"] += [t.data]

        #int8_t zero[28];
        #uint16_t terrain_count_additional;
        zero_terrain_count_struct = Struct(endianness + "28c H")
        pc = zero_terrain_count_struct.unpack_from(raw, offset)
        offset += zero_terrain_count_struct.size

        self.data["terrain_count_additional"] = pc[28]

        tmp_struct = Struct(endianness + "12722s")
        t = tmp_struct.unpack_from(raw, offset)
        offset_begin = offset
        offset += tmp_struct.size

        fname = 'raw/terrain_render_data_%d_to_%d.raw' % (offset_begin, offset)
        filename = file_get_path(fname, write=True)
        file_write(filename, t[0])

        return offset

开发者ID:jcaesar,项目名称:openage,代码行数:29,代码来源:terrain.py

示例2: read

▲ 点赞 7 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
    def read(self, raw, offset):
        self.data = dict()

        #int32_t id;
        #int8_t unknown;
        #int32_t upper_building;
        #int32_t required_researches;
        #int32_t age;
        #int32_t unit_or_research0;
        #int32_t unit_or_research1;
        #int32_t unknown[8];
        #int32_t mode0;
        #int32_t mode1;
        #int32_t unknown[7];
        #int32_t vertical_line;
        #int8_t unit_count;
        unit_connection_struct = Struct(endianness + "i b 5i 8i 2i 7i i b")

        pc = unit_connection_struct.unpack_from(raw, offset)
        offset_info(offset, pc, "uconnection: id X upperbuilding req_researches age ur0 ur1 X[8] mode0 mode1 X[7] verticalline unitcount", unit_connection_struct)
        offset += unit_connection_struct.size

        self.data["id"]                  = pc[0]
        #self.data[""] = pc[1]
        self.data["upper_building"]      = pc[2]
        self.data["required_researches"] = pc[3]
        self.data["age"]                 = pc[4]
        self.data["unit_or_research0"]   = pc[5]
        self.data["unit_or_research1"]   = pc[6]
        #self.data[""] = pc[7:(7+8)]
        self.data["mode0"]               = pc[15]
        self.data["mode1"]               = pc[16]
        #self.data[""] = pc[17:(17+7)]
        self.data["vertical_line"]       = pc[24]
        self.data["unit_count"]          = pc[25]

        #int32_t unit[unit_count];
        unit_connection_struct = Struct(endianness + "%di" % self.data["unit_count"])
        pc = unit_connection_struct.unpack_from(raw, offset)
        offset_info(offset, pc, "uconnection: unit", unit_connection_struct, 1)
        offset += unit_connection_struct.size

        self.data["unit"] = pc

        #int32_t location_in_age;
        #int32_t required_research;
        #int32_t line_mode;
        #int32_t enabling_research;
        unit_connection_struct = Struct(endianness + "4i")

        pc = unit_connection_struct.unpack_from(raw, offset)
        offset_info(offset, pc, "uconnection: locationinage requiredresearch linemode enablingresearch", unit_connection_struct)
        offset += unit_connection_struct.size

        self.data["location_in_age"]   = pc[0]
        self.data["required_research"] = pc[1]
        self.data["line_mode"]         = pc[2]
        self.data["enabling_research"] = pc[3]

        return offset

开发者ID:jcaesar,项目名称:openage,代码行数:62,代码来源:tech.py

示例3: unpack

▲ 点赞 5 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
    def unpack(self, data):
        # structure taken from cryptfs.h in crespo source.
        s = Struct('<'+'L H H')
        ftrMagic, majorVersion, minorVersion = s.unpack_from(data)
        if minorVersion < SCRYPT_ADDED_MINOR:
            s = Struct('<'+'L H H L L L L L L L 64s L 48s 16s')
            (self.ftrMagic, self.majorVersion, self.minorVersion, 
            self.ftrSize, self.flags, self.keySize, self.spare1, 
            self.fsSize1, self.fsSize2, self.failedDecrypt, self.cryptoType, 
            self.spare2, self.cryptoKey, self.cryptoSalt) = s.unpack_from(data)

            self.cryptoKey = self.cryptoKey[0:self.keySize]
        else:
            s = Struct('<'+'L H H L L L L L L L 64s L 48s 16s 2Q L B B B B')
            (self.ftrMagic, self.majorVersion, self.minorVersion, self.ftrSize,
 			self.flags, self.keySize, self.spare1, self.fsSize1, self.fsSize2, 
            self.failedDecrypt, self.cryptoType, self.spare2, self.cryptoKey, 
            self.cryptoSalt, self.persistDataOffset1, self.persistDataOffset2, 
            self.persistDataSize, self.kdf, self.N_factor, self.r_factor, 
            self.p_factor) = s.unpack_from(data)

            self.cryptoKey = self.cryptoKey[0:self.keySize]
            self.N = 1 << self.N_factor
            self.r = 1 << self.r_factor
            self.p = 1 << self.p_factor

开发者ID:Gilgamash099,项目名称:Santoku-Linux,代码行数:27,代码来源:bruteforce_stdcrypto.py

示例4: read

▲ 点赞 2 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
    def read(self, raw, offset):
        self.data = dict()

        #bool exists;
        unit_header_header_struct0 = Struct(endianness + "?")

        pc = unit_header_header_struct0.unpack_from(raw, offset)
        offset += unit_header_header_struct0.size

        self.data["exists"] = pc[0]

        if self.data["exists"] == True:
            unit_header_header_struct1 = Struct(endianness + "H")

            pc = unit_header_header_struct1.unpack_from(raw, offset)
            offset += unit_header_header_struct1.size

            self.data["unit_command_count"] = pc[0]

            self.data["unit_command"] = list()
            for i in range(self.data["unit_command_count"]):
                t = UnitCommand()
                offset = t.read(raw, offset)
                self.data["unit_command"] += [t.data]

        return offset

开发者ID:jcaesar,项目名称:openage,代码行数:28,代码来源:unit.py

示例5: read

▲ 点赞 1 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
    def read(self, raw, offset):
        self.data = dict()

        #uint16_t graphic_count;
        header_struct = Struct(endianness + "H")

        self.data["graphic_count"], = header_struct.unpack_from(raw, offset)
        offset += header_struct.size

        #int32_t graphic_offset[graphic_count];
        offset_struct = Struct(endianness + "%di" % self.data["graphic_count"])

        self.data["graphic_offset"] = offset_struct.unpack_from(raw, offset)
        offset += offset_struct.size

        self.data["graphic"] = list()
        for i in range(self.data["graphic_count"]):
            g_offset = self.data["graphic_offset"][i]
            if g_offset == 0:
                #dbg("SKIPPING graphic %d" % i)
                continue

            t = Graphic()
            offset = t.read(raw, offset)
            self.data["graphic"] += [t.data]

        #int8_t[138] rendering_data;
        rendering_data_struct = Struct(endianness + "138c")

        self.data["rendering_data"] = rendering_data_struct.unpack_from(raw, offset)
        offset += rendering_data_struct.size

        return offset

开发者ID:jcaesar,项目名称:openage,代码行数:35,代码来源:graphic.py

示例6: leapseconds

▲ 点赞 1 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
def leapseconds(tzfiles=['/usr/share/zoneinfo/right/UTC',
                         '/usr/lib/zoneinfo/right/UTC'],
                use_fallback=True):
    """Extract leap seconds from *tzfiles*."""
    for filename in tzfiles:
        try:
            file = open(filename, 'rb')
        except IOError:
            continue
        else:
            break
    else:  # no break
        if not use_fallback:
            raise ValueError('Unable to open any tzfile: %s' % (tzfiles,))
        else:
            return _fallback()

    with file:
        header = Struct('>4s c 15x 6i')  # see struct tzhead above
        (magic, version, _, _, leapcnt, timecnt, typecnt,
         charcnt) = header.unpack_from(file.read(header.size))
        if magic != "TZif".encode():
            raise ValueError('Wrong magic %r in tzfile: %s' % (
                magic, file.name))
        if version not in '\x0023'.encode():
            warn('Unsupported version %r in tzfile: %s' % (
                version, file.name), RuntimeWarning)
        if leapcnt == 0:
            raise ValueError("No leap seconds in tzfile: %s" % (
                file.name))

        """# from tzfile.h[2] (the file is in public domain)

         . . .header followed by. . .

         tzh_timecnt (char [4])s  coded transition times a la time(2)
         tzh_timecnt (unsigned char)s types of local time starting at above
         tzh_typecnt repetitions of
           one (char [4])  coded UT offset in seconds
           one (unsigned char) used to set tm_isdst
           one (unsigned char) that's an abbreviation list index
         tzh_charcnt (char)s  '\0'-terminated zone abbreviations
         tzh_leapcnt repetitions of
           one (char [4])  coded leap second transition times
           one (char [4])  total correction after above
        """
        file.read(timecnt * 5 + typecnt * 6 + charcnt)  # skip

        result = [LeapSecond(datetime(1972, 1, 1), timedelta(seconds=10))]
        nleap_seconds = 10
        tai_epoch_as_tai = datetime(1970, 1, 1, 0, 0, 10)
        buf = Struct(">2i")
        for _ in range(leapcnt):  # read leap seconds
            t, cnt = buf.unpack_from(file.read(buf.size))
            dTAI_UTC = nleap_seconds + cnt
            utc = tai_epoch_as_tai + timedelta(seconds=t - dTAI_UTC + 1)
            assert utc - datetime(utc.year, utc.month, utc.day) == timedelta(0)
            result.append(LeapSecond(utc, timedelta(seconds=dTAI_UTC)))
        result.append(sentinel)
        return result

开发者ID:FakeAstronaut,项目名称:Moon,代码行数:62,代码来源:leapseconds.py

示例7: read

▲ 点赞 1 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
    def read(self, raw, offset):
        self.data = dict()

        #int16_t[6] required_techs;
        research0_struct = Struct(endianness + "6h")

        pc = research0_struct.unpack_from(raw, offset)
        offset += research0_struct.size

        self.data["required_techs"] = pc[0]

        self.data["research_ressource_cost"] = list()
        for i in range(3):
            t = ResearchRessourceCost()
            offset = t.read(raw, offset)
            self.data["research_ressource_cost"] += [t.data]


        #int16_t required_tech_count;
        #int16_t civilisation_id;
        #int16_t full_tech_mode;
        #int16_t research_location_id;
        #uint16_t language_dll_name;
        #uint16_t language_dll_description;
        #int16_t research_time;
        #int16_t tech_id;
        #int16_t tech_type;
        #int16_t icon_id;
        #int8_t button_id;
        #int32_t pointers[3];
        #uint16_t name_length;
        research1_struct = Struct(endianness + "4h 2H 4h b 3i H")

        pc = research1_struct.unpack_from(raw, offset)
        offset += research1_struct.size

        self.data["required_tech_count"] = pc[0]
        self.data["civilisation_id"] = pc[1]
        self.data["full_tech_mode"] = pc[2]
        self.data["research_location_id"] = pc[3]
        self.data["language_dll_name"] = pc[4]
        self.data["language_dll_description"] = pc[5]
        self.data["research_time"] = pc[6]
        self.data["tech_id"] = pc[7]
        self.data["tech_type"] = pc[8]
        self.data["icon_id"] = pc[9]
        self.data["button_id"] = pc[10]
        self.data["pointers"] = pc[11:(11+3)]
        self.data["name_length"] = pc[14]

        research_name_struct = Struct(endianness + "%ds" % self.data["name_length"])

        pc = research_name_struct.unpack_from(raw, offset)
        offset += research_name_struct.size

        #char name[name_length];
        self.data["name"] = zstr(pc[0])

        return offset

开发者ID:jcaesar,项目名称:openage,代码行数:61,代码来源:research.py

示例8: parse_sol_files

▲ 点赞 1 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
def parse_sol_files(sol_files):
    results = []
    for sol_file in sol_files:
        print("Reading Flash state file: {0}\n".format(sol_file))
        with open(sol_file, 'rb') as f:
            data = f.read()

        # What follows is a limited parser for Flash Local Shared Object files -
        # a more complete implementation may be found at:
        # https://pypi.python.org/pypi/PyAMF
        header = Struct('>HI10s8sI')
        magic, objlength, magic2, mjinfo, padding = header.unpack_from(data)
        offset = header.size
        assert magic == 0xbf
        assert magic2 == b'TCSO\0\x04\0\0\0\0'
        assert mjinfo == b'\0\x06mjinfo'
        assert padding == 0
        ushort = Struct('>H')
        ubyte = Struct('>B')
        while offset < len(data):
            length, = ushort.unpack_from(data, offset)
            offset += ushort.size
            name = data[offset:offset+length]
            offset += length
            amf0_type, = ubyte.unpack_from(data, offset)
            offset += ubyte.size
            # Type 2: UTF-8 String, prefixed with 2-byte length
            if amf0_type == 2:
                length, = ushort.unpack_from(data, offset)
                offset += ushort.size
                value = data[offset:offset+length]
                offset += length
            # Type 6: Undefined
            elif amf0_type == 6:
                value = None
            # Type 1: Boolean
            elif amf0_type == 1:
                value = bool(data[offset])
                offset += 1
            # Other types from the AMF0 specification are not implemented, as they
            # have not been observed in mjinfo.sol files. If required, see
            # http://download.macromedia.com/pub/labs/amf/amf0_spec_121207.pdf
            else:
                print("Unimplemented AMF0 type {} at offset={} (hex {})".format(amf0_type, offset, hex(offset)))
            trailer_byte = data[offset]
            assert trailer_byte == 0
            offset += 1
            if name == b'logstr':
                results = filter(None, value.split(b'\n'))

        results = [i.decode('ASCII') for i in results]

    return results

开发者ID:MahjongRepository,项目名称:tenhou-log-collector,代码行数:55,代码来源:collect.py

示例9: _get_font_name

▲ 点赞 1 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
def _get_font_name(file_path):
    try:
        #customize path
        f = open(file_path, 'rb')
        #header
        shead = Struct('>IHHHH')
        fhead = f.read(shead.size)
        dhead = shead.unpack_from(fhead, 0)

        #font directory
        stable = Struct('>4sIII')
        ftable = f.read(stable.size * dhead[1])
        for i in range(dhead[1]): 
            #directory records
            dtable = stable.unpack_from(ftable, i * stable.size)
            if dtable[0] == 'name':
                break
        assert dtable[0] == 'name'

        #name table
        f.seek(dtable[2]) #at offset
        fnametable = f.read(dtable[3]) #length
        snamehead = Struct('>HHH') #name table head
        dnamehead = snamehead.unpack_from(fnametable, 0)

        sname = Struct('>HHHHHH')
    except:
        return {}
    NAME_ID = { 1: 'family_name', 4: 'full_name', 6: 'postscript_name' }

    result = {}

    for i in range(dnamehead[1]):
        #name table records
        dname = sname.unpack_from(fnametable, snamehead.size + i * sname.size)
        if dname[3] in NAME_ID:
            _name = unpack_from('%is' % dname[4], fnametable, dnamehead[2] + dname[5])[0]
            try:
                if dname[2] > 0:
                    _name = _name.decode('utf-16-be')
            except:
                pass
            try:
                _name = _name or _name.decode('mbcs')
            except:
                pass
            result.update({ NAME_ID[dname[3]]: _name })
    _compact_full_name = result[NAME_ID[4]].replace(' ', '')
    if NAME_ID[6] not in result or len(_compact_full_name) > len(result[NAME_ID[6]]):
        result.update({NAME_ID[6]: _compact_full_name })
    return result

开发者ID:Xiongpq,项目名称:FontCenter,代码行数:53,代码来源:FontListViews.py

示例10: unpack_records

▲ 点赞 1 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
def unpack_records(format, data):
    """
    Yield the records contained in a binary string
    """
    record_struct = Struct(format)
    for offset in range(0, len(data), record_struct.size):
        yield record_struct.unpack_from(data, offset)

开发者ID:lekum,项目名称:python-snippets,代码行数:9,代码来源:main.py

示例11: read

▲ 点赞 1 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
    def read(self, raw, offset):
        self.data = dict()

        #int32_t id;
        #int32_t palette;
        #int32_t color;
        #int32_t unknown;
        #int32_t unknown;
        #int32_t minimap_color;
        #int32_t unknown;
        #int32_t unknown;
        #int32_t unknown;
        player_color_struct = Struct(endianness + "9i")

        pc = player_color_struct.unpack_from(raw, offset)
        offset += player_color_struct.size

        self.data["id"]            = pc[0]
        self.data["palette"]       = pc[1]
        self.data["color"]         = pc[2]
        #self.data[""] = pc[0]
        #self.data[""] = pc[0]
        self.data["minimap_color"] = pc[5]
        #self.data[""] = pc[0]
        #self.data[""] = pc[0]

        return offset

开发者ID:jcaesar,项目名称:openage,代码行数:29,代码来源:playercolor.py

示例12: _unpack_symblock

▲ 点赞 1 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
    def _unpack_symblock(self, offset):
        code = Struct('>H')
        self._fobj.seek(self._start_offset + offset)
        blk = self.sym_block_fmt.unpack_file(self._fobj)
        print blk

        self.sym_block = []
        assert blk.divider == -1
        assert blk.block_id == 1
        blk_data = self._fobj.read(blk.block_len - 6) # 6 for len and nlayers
        layer_off = 0
        for l in range(blk.nlayer):
            layer_hdr = self.sym_layer_fmt.unpack_from(blk_data, layer_off)
            print layer_hdr
            assert layer_hdr.divider == -1
            layer_off += self.sym_layer_fmt.size
            layer_data = blk_data[layer_off:layer_off + layer_hdr.length]
            layer_off += layer_hdr.length
            
            data_off = 0
            layer = []
            self.sym_block.append(layer)
            while data_off < len(layer_data):
                packet_code, = code.unpack_from(layer_data, data_off)
                data_off += code.size
                print packet_code, '%x' % packet_code
                data,size = self.packet_map[packet_code](layer_data[data_off:])
                layer.append(data)
                data_off += size

开发者ID:rayg-ssec,项目名称:MetPy,代码行数:31,代码来源:nexrad.py

示例13: init

▲ 点赞 1 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
class Block:
    def __init__(self, structure, encoding):
        self._structure = structure
        self._encoding = encoding
        # Create a new Struct object to correctly read the binary data in this
        # block in particular, pass it along that it is a little endian (<),
        # along with all expected fields.
        self._compiled = Struct("<" + "".join(
            [field.format for field in self._structure]))
        self.size = self._compiled.size

    def unpack(self, buffer, offset=0):
        # Use the Struct to read the binary data in the buffer
        # where this block appears at the given offset.
        values = self._compiled.unpack_from(buffer, offset)
        # Match up each value with the corresponding field in the block
        # and put it in a dictionary for easy reference.
        return {field.field_name: value for value, field in
                zip(values, self._structure)}

    def _unpack_from_file(self, file, offset=None):
        if offset is not None:
            # move the pointer in the file to the specified offset;
            # this is not index 0
            file.seek(offset)
        # read in the amount of data corresponding to the block size
        buffer = file.read(self.size)
        # return the values of the fields after unpacking them
        return self.unpack(buffer)

    def unpack_from_file(self, file, seek=None):
        # When more advanced behaviour is needed,
        # this method can be overridden by subclassing.
        return self._unpack_from_file(file, seek)

开发者ID:kimbauters,项目名称:ZIMply,代码行数:36,代码来源:zimply.py

示例14: __extract_fdt_header

▲ 点赞 1 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
 def __extract_fdt_header(self):
     """Extract DTB header"""
     header = Struct(self.__fdt_header_format)
     header_entry = Struct(">I")
     data = self.infile.read(header.size)
     result = dict(zip(self.__fdt_header_names, header.unpack_from(data)))
     if result['version'] >= 2:
         data = self.infile.read(header_entry.size)
         result['boot_cpuid_phys'] = header_entry.unpack_from(data)[0]
     if result['version'] >= 3:
         data = self.infile.read(header_entry.size)
         result['size_dt_strings'] = header_entry.unpack_from(data)[0]
     if result['version'] >= 17:
         data = self.infile.read(header_entry.size)
         result['size_dt_struct'] = header_entry.unpack_from(data)[0]
     return result

开发者ID:superna9999,项目名称:pyfdt,代码行数:18,代码来源:pyfdt.py

示例15: init

▲ 点赞 1 ▼

# 需要导入模块: from struct import Struct [as 别名]
# 或者: from struct.Struct import unpack_from [as 别名]
    def __init__(self, fname):
        self.fname = fname
        dbg("reading blendomatic data from %s" % fname, 1, push="blendomatic")

        fname = file_get_path(fname, write=False)
        f = file_open(fname, binary=True, write=False)

        buf = f.read(Blendomatic.blendomatic_header.size)
        self.header = Blendomatic.blendomatic_header.unpack_from(buf)

        blending_mode_count, tile_count = self.header

        dbg("%d blending modes, each %d tiles" % (blending_mode_count, tile_count), 2)

        blending_mode = Struct(endianness + "I %dB" % (tile_count))

        self.blending_modes = list()

        for i in range(blending_mode_count):
            header_data  = f.read(blending_mode.size)
            bmode_header = blending_mode.unpack_from(header_data)

            new_mode = BlendingMode(i, f, tile_count, bmode_header)

            self.blending_modes.append(new_mode)

        f.close()
        dbg(pop="blendomatic")

开发者ID:ArseniyShestakov,项目名称:openage,代码行数:30,代码来源:blendomatic.py

注:本文中的struct.Struct.unpack_from方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。