当前位置: 首页>>代码示例>>Python>>正文


Python struct.pack_into方法代码示例

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


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

示例1: _authenticate

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def _authenticate(sock, user, password, password_field_id):
    user = str_to_bytes(user)
    password = str_to_bytes(password)
    sz = len(user) + len(password) + 34 # 2 * 5 + 24
    send_buf = _admin_write_header(sz, _AUTHENTICATE, 2)
    fmt_str = "! I B %ds I B %ds" % (len(user), len(password))
    struct.pack_into(fmt_str, send_buf, _HEADER_SIZE,
                     len(user) + 1, _USER_FIELD_ID, user,
                     len(password) + 1, password_field_id, password)
    try:
        # OpenSSL wrapper doesn't support ctypes
        send_buf = _buffer_to_string(send_buf)
        sock.sendall(send_buf)
        recv_buff = _receivedata(sock, _HEADER_SIZE)
        rv = _admin_parse_header(recv_buff)
        return rv[2]
    except Exception as ex:
        raise IOError("Error: %s" % str(ex)) 
开发者ID:aerospike,项目名称:aerospike-admin,代码行数:20,代码来源:info.py

示例2: test_pack_into_fn

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def test_pack_into_fn(self):
        test_string = 'Reykjavik rocks, eow!'
        writable_buf = array.array('c', ' '*100)
        fmt = '21s'
        pack_into = lambda *args: struct.pack_into(fmt, *args)

        # Test without offset.
        pack_into(writable_buf, 0, test_string)
        from_buf = writable_buf.tostring()[:len(test_string)]
        self.assertEqual(from_buf, test_string)

        # Test with offset.
        pack_into(writable_buf, 10, test_string)
        from_buf = writable_buf.tostring()[:len(test_string)+10]
        self.assertEqual(from_buf, test_string[:10] + test_string)

        # Go beyond boundaries.
        small_buf = array.array('c', ' '*10)
        self.assertRaises((ValueError, struct.error), pack_into, small_buf, 0,
                          test_string)
        self.assertRaises((ValueError, struct.error), pack_into, small_buf, 2,
                          test_string) 
开发者ID:IronLanguages,项目名称:ironpython2,代码行数:24,代码来源:test_struct.py

示例3: write_header

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def write_header(self, use_compression_type=True):
        batch_len = len(self._buffer)
        self.HEADER_STRUCT.pack_into(
            self._buffer, 0,
            0,  # BaseOffset, set by broker
            batch_len - self.AFTER_LEN_OFFSET,  # Size from here to end
            self.NO_PARTITION_LEADER_EPOCH,
            self._magic,
            0,  # CRC will be set below, as we need a filled buffer for it
            self._get_attributes(use_compression_type),
            self._last_offset,
            self._first_timestamp or 0,
            self._max_timestamp or 0,
            self._producer_id,
            self._producer_epoch,
            self._base_sequence,
            self._num_records
        )
        crc = calc_crc32c(self._buffer[self.ATTRIBUTES_OFFSET:])
        struct.pack_into(">I", self._buffer, self.CRC_OFFSET, crc) 
开发者ID:robinhood,项目名称:aiokafka,代码行数:22,代码来源:default_records.py

示例4: test_read_log_append_time_v1

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def test_read_log_append_time_v1():
    buffer = _make_compressed_batch(1)

    # As Builder does not support creating data with `timestamp_type==1` we
    # patch the result manually

    buffer[ATTRIBUTES_OFFSET] |= TIMESTAMP_TYPE_MASK
    expected_timestamp = 10000000
    struct.pack_into(">q", buffer, TIMESTAMP_OFFSET, expected_timestamp)

    batch = LegacyRecordBatch(buffer, 1)
    msgs = list(batch)

    for offset, msg in enumerate(msgs):
        assert msg.offset == offset
        assert msg.timestamp == expected_timestamp
        assert msg.timestamp_type == 1 
开发者ID:robinhood,项目名称:aiokafka,代码行数:19,代码来源:test_legacy.py

示例5: test_pack_into_fn

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def test_pack_into_fn(self):
        test_string = b'Reykjavik rocks, eow!'
        writable_buf = array.array('b', b' '*100)
        fmt = '21s'
        pack_into = lambda *args: struct.pack_into(fmt, *args)

        # Test without offset.
        pack_into(writable_buf, 0, test_string)
        from_buf = writable_buf.tobytes()[:len(test_string)]
        self.assertEqual(from_buf, test_string)

        # Test with offset.
        pack_into(writable_buf, 10, test_string)
        from_buf = writable_buf.tobytes()[:len(test_string)+10]
        self.assertEqual(from_buf, test_string[:10] + test_string)

        # Go beyond boundaries.
        small_buf = array.array('b', b' '*10)
        self.assertRaises((ValueError, struct.error), pack_into, small_buf, 0,
                          test_string)
        self.assertRaises((ValueError, struct.error), pack_into, small_buf, 2,
                          test_string) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:24,代码来源:test_struct.py

示例6: test_trailing_counter

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def test_trailing_counter(self):
        store = array.array('b', b' '*100)

        # format lists containing only count spec should result in an error
        self.assertRaises(struct.error, struct.pack, '12345')
        self.assertRaises(struct.error, struct.unpack, '12345', '')
        self.assertRaises(struct.error, struct.pack_into, '12345', store, 0)
        self.assertRaises(struct.error, struct.unpack_from, '12345', store, 0)

        # Format lists with trailing count spec should result in an error
        self.assertRaises(struct.error, struct.pack, 'c12345', 'x')
        self.assertRaises(struct.error, struct.unpack, 'c12345', 'x')
        self.assertRaises(struct.error, struct.pack_into, 'c12345', store, 0,
                           'x')
        self.assertRaises(struct.error, struct.unpack_from, 'c12345', store,
                           0)

        # Mixed format tests
        self.assertRaises(struct.error, struct.pack, '14s42', 'spam and eggs')
        self.assertRaises(struct.error, struct.unpack, '14s42',
                          'spam and eggs')
        self.assertRaises(struct.error, struct.pack_into, '14s42', store, 0,
                          'spam and eggs')
        self.assertRaises(struct.error, struct.unpack_from, '14s42', store, 0) 
开发者ID:Microvellum,项目名称:Fluid-Designer,代码行数:26,代码来源:test_struct.py

示例7: pack

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def pack(self, addr, fmt, *data):
        """
        Use the ``struct`` module to pack `data` into memory at address `addr` with the format `fmt`.
        """

        try:
            start, backer = next(self.backers(addr))
        except StopIteration:
            raise KeyError(addr)

        if start > addr:
            raise KeyError(addr)

        try:
            return struct.pack_into(fmt, backer, addr - start, *data)
        except struct.error as e:
            if len(backer) - (addr - start) >= struct.calcsize(fmt):
                raise e
            raise KeyError(addr) 
开发者ID:angr,项目名称:cle,代码行数:21,代码来源:memory.py

示例8: SaveEntrances

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def SaveEntrances(self):
        """
        Saves the entrances back to block 7
        """
        offset = 0
        entstruct = struct.Struct('>HHhhBBBBBBxBHBBBBBx')
        buffer = bytearray(len(self.entrances) * 24)
        zonelist = self.zones
        for entrance in self.entrances:
            zoneID = SLib.MapPositionToZoneID(zonelist, entrance.objx, entrance.objy)
            try:
                entstruct.pack_into(buffer, offset, int(entrance.objx), int(entrance.objy), int(entrance.camerax),
                                    int(entrance.cameray), int(entrance.entid), int(entrance.destarea), int(entrance.destentrance),
                                    int(entrance.enttype), int(entrance.players), zoneID, int(entrance.playerDistance),
                                    int(entrance.entsettings), int(entrance.otherID), int(entrance.coinOrder),
                                    int(entrance.pathID), int(entrance.pathnodeindex), int(entrance.transition))
            except struct.error:
                if zoneID < 0:
                    raise ValueError('Entrance %d at (%d, %d) is too far from any zone\'s boundaries!\nPlease place it near a zone.' % (entrance.entid, int(entrance.objx), int(entrance.objy))) from None
                else:
                    raise ValueError('SaveEntrances struct.error.')
            offset += 24
        self.blocks[6] = bytes(buffer) 
开发者ID:aboood40091,项目名称:Miyamoto,代码行数:25,代码来源:area.py

示例9: SaveLoadedSprites

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def SaveLoadedSprites(self):
        """
        Saves the list of loaded sprites back to block 9
        """
        ls = []
        for sprite in self.sprites:
            if sprite.type not in ls: ls.append(sprite.type)
        ls.sort()

        offset = 0
        sprstruct = struct.Struct('>Hxx')
        buffer = bytearray(len(ls) * 4)
        for s in ls:
            sprstruct.pack_into(buffer, offset, int(s))
            offset += 4
        self.blocks[8] = bytes(buffer) 
开发者ID:aboood40091,项目名称:Miyamoto,代码行数:18,代码来源:area.py

示例10: set_environmental_data

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def set_environmental_data(self, humidity, temperature):
        """Set the temperature and humidity used when computing eCO2 and TVOC values.

        :param int humidity: The current relative humidity in percent.
        :param float temperature: The current temperature in Celsius."""
        # Humidity is stored as an unsigned 16 bits in 1/512%RH. The default
        # value is 50% = 0x64, 0x00. As an example 48.5% humidity would be 0x61,
        # 0x00.
        humidity = int(humidity * 512)

        # Temperature is stored as an unsigned 16 bits integer in 1/512 degrees
        # there is an offset: 0 maps to -25C. The default value is 25C = 0x64,
        # 0x00. As an example 23.5% temperature would be 0x61, 0x00.
        temperature = int((temperature + 25) * 512)

        buf = bytearray(5)
        buf[0] = _ENV_DATA
        struct.pack_into(">HH", buf, 1, humidity, temperature)

        with self.i2c_device as i2c:
            i2c.write(buf) 
开发者ID:adafruit,项目名称:Adafruit_CircuitPython_CCS811,代码行数:23,代码来源:adafruit_ccs811.py

示例11: setUp_with_echo

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def setUp_with_echo(self):
        self.echo_id = 13379
        self.echo_seq = 1
        self.echo_data = b'\x30\x0e\x09\x00\x00\x00\x00\x00' \
            + b'\x10\x11\x12\x13\x14\x15\x16\x17' \
            + b'\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f' \
            + b'\x20\x21\x22\x23\x24\x25\x26\x27' \
            + b'\x28\x29\x2a\x2b\x2c\x2d\x2e\x2f' \
            + b'\x30\x31\x32\x33\x34\x35\x36\x37'
        self.data = icmp.echo(
            id_=self.echo_id, seq=self.echo_seq, data=self.echo_data)

        self.type_ = icmp.ICMP_ECHO_REQUEST
        self.code = 0
        self.ic = icmp.icmp(self.type_, self.code, self.csum, self.data)

        self.buf = bytearray(struct.pack(
            icmp.icmp._PACK_STR, self.type_, self.code, self.csum))
        self.buf += self.data.serialize()
        self.csum_calc = packet_utils.checksum(self.buf)
        struct.pack_into('!H', self.buf, 2, self.csum_calc) 
开发者ID:OpenState-SDN,项目名称:ryu,代码行数:23,代码来源:test_icmp.py

示例12: setUp_with_dest_unreach

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def setUp_with_dest_unreach(self):
        self.unreach_mtu = 10
        self.unreach_data = b'abc'
        self.unreach_data_len = len(self.unreach_data)
        self.data = icmp.dest_unreach(
            data_len=self.unreach_data_len, mtu=self.unreach_mtu,
            data=self.unreach_data)

        self.type_ = icmp.ICMP_DEST_UNREACH
        self.code = icmp.ICMP_HOST_UNREACH_CODE
        self.ic = icmp.icmp(self.type_, self.code, self.csum, self.data)

        self.buf = bytearray(struct.pack(
            icmp.icmp._PACK_STR, self.type_, self.code, self.csum))
        self.buf += self.data.serialize()
        self.csum_calc = packet_utils.checksum(self.buf)
        struct.pack_into('!H', self.buf, 2, self.csum_calc) 
开发者ID:OpenState-SDN,项目名称:ryu,代码行数:19,代码来源:test_icmp.py

示例13: initial_connection

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def initial_connection(self, data):
        state = self._connection
        state.ssrc = data['ssrc']
        state.voice_port = data['port']
        state.endpoint_ip = data['ip']

        packet = bytearray(70)
        struct.pack_into('>I', packet, 0, state.ssrc)
        state.socket.sendto(packet, (state.endpoint_ip, state.voice_port))
        recv = await self.loop.sock_recv(state.socket, 70)
        log.debug('received packet in initial_connection: %s', recv)

        # the ip is ascii starting at the 4th byte and ending at the first null
        ip_start = 4
        ip_end = recv.index(0, ip_start)
        state.ip = recv[ip_start:ip_end].decode('ascii')

        state.port = struct.unpack_from('>H', recv, len(recv) - 2)[0]
        log.debug('detected ip: %s port: %s', state.ip, state.port)

        # there *should* always be at least one supported mode (xsalsa20_poly1305)
        modes = [mode for mode in data['modes'] if mode in self._connection.supported_modes]
        log.debug('received supported encryption modes: %s', ", ".join(modes))

        mode = modes[0]
        await self.select_protocol(state.ip, state.port, mode)
        log.info('selected the voice protocol for use (%s)', mode)

        await self.client_connect() 
开发者ID:Rapptz,项目名称:discord.py,代码行数:31,代码来源:gateway.py

示例14: _get_voice_packet

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def _get_voice_packet(self, data):
        header = bytearray(12)

        # Formulate rtp header
        header[0] = 0x80
        header[1] = 0x78
        struct.pack_into('>H', header, 2, self.sequence)
        struct.pack_into('>I', header, 4, self.timestamp)
        struct.pack_into('>I', header, 8, self.ssrc)

        encrypt_packet = getattr(self, '_encrypt_' + self.mode)
        return encrypt_packet(header, data) 
开发者ID:Rapptz,项目名称:discord.py,代码行数:14,代码来源:voice_client.py

示例15: _admin_write_header

# 需要导入模块: import struct [as 别名]
# 或者: from struct import pack_into [as 别名]
def _admin_write_header(sz, command, field_count):
    send_buf = create_string_buffer(sz)      # from ctypes
    sz = (_ADMIN_MSG_VERSION << 56) | (_ADMIN_MSG_TYPE << 48) | (sz - 8)

    if g_struct_admin_header_out != None:
        g_struct_admin_header_out.pack_into(
            send_buf, 0, sz, 0, 0, command, field_count)
    else:
        struct.pack_into(
            admin_header_fmt, send_buf, 0, sz, 0, 0, command, field_count)

    return send_buf 
开发者ID:aerospike,项目名称:aerospike-admin,代码行数:14,代码来源:info.py


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