• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python struct._pack函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中struct._pack函数的典型用法代码示例。如果您正苦于以下问题:Python _pack函数的具体用法?Python _pack怎么用?Python _pack使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



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

示例1: funcall

    def funcall(self, oid, *args):
        """
        Low-level call to PostgreSQL function, you must supply
        the oid of the function, and have the args supplied as
        ints or strings.

        """
        if DEBUG:
            funcname = self.__lo_funcnames.get(oid, str(oid))
            print "funcall", funcname, args

        self.__ready = 0
        self.__send(_pack("!2sIi", "F\0", oid, len(args)))
        for arg in args:
            atype = type(arg)
            if (atype == types.LongType) and (arg >= 0):
                # Make sure positive longs, such as OIDs, get sent back as unsigned ints
                self.__send(_pack("!iI", 4, arg))
            elif (atype == types.IntType) or (atype == types.LongType):
                self.__send(_pack("!ii", 4, arg))
            else:
                self.__send(_pack("!i", len(arg)))
                self.__send(arg)

        while not self.__ready:
            self.__read_response()
        result, self.__func_result = self.__func_result, None
        return result
开发者ID:ddimmich,项目名称:Cubulus,代码行数:28,代码来源:bpgsql.py


示例2: funcall

    def funcall(self, oid, *args):
        """
        Low-level call to PostgreSQL function, you must supply
        the oid of the function, and have the args supplied as
        ints or strings.

        """
        self.__ready = 0
        self.__send(_pack('!2sIi', 'F\0', oid, len(args)))
        for arg in args:
            atype = type(arg)
            if (atype == int) and (arg >= 0):
                # Make sure positive longs, such as OIDs, get
                # sent back as unsigned ints
                self.__send(_pack('!iI', 4, arg))
            elif (atype == int) or (atype == int):
                self.__send(_pack('!ii', 4, arg))
            else:
                self.__send(_pack('!i', len(arg)))
                self.__send(arg)

        while not self.__ready:
            self.__read_response()
        result, self.__func_result = self.__func_result, None
        return result
开发者ID:seanjensengrey,项目名称:bpgsql,代码行数:25,代码来源:bpgsql.py


示例3: _varintEncode

def _varintEncode(n):
	if n < 0xfd:
		return _pack('<B', n)
	# NOTE: Technically, there are more encodings for numbers bigger than
	# 16-bit, but transaction counts can't be that high with version 2 Bitcoin
	# blocks
	return b'\xfd' + _pack('<H', n)
开发者ID:luke-jr,项目名称:python-blkmaker,代码行数:7,代码来源:blkmaker.py


示例4: _pkt_R

    def _pkt_R(self):
        #
        # Startup Response
        #
        code = _unpack('!i', self.__read_bytes(4))[0]
        if code == 0:
            self.__authenticated = 1
            #print 'Authenticated!'
        elif code == 1:
            raise InterfaceError('Kerberos V4 authentication is required by server, but not supported by this client')
        elif code == 2:
            raise InterfaceError('Kerberos V5 authentication is required by server, but not supported by this client')
        elif code == 3:
            self.__send(_pack('!i', len(self.__passwd)+5) + self.__passwd + '\0')
        elif code == 4:
            salt = self.__read_bytes(2)
            try:
                import crypt
            except:
                raise InterfaceError('Encrypted authentication is required by server, but Python crypt module not available')
            cpwd = crypt.crypt(self.__passwd, salt)
            self.__send(_pack('!i', len(cpwd)+5) + cpwd + '\0')
        elif code == 5:
            import md5

            m = md5.new(self.__passwd + self.__userid).hexdigest()
            m = md5.new(m + self.__read_bytes(4)).hexdigest()
            m = 'md5' + m + '\0'
            self.__send(_pack('!i', len(m)+4) + m)
        else:
            raise InterfaceError('Unknown startup response code: R%d (unknown password encryption?)' % code)
开发者ID:seanjensengrey,项目名称:bpgsql,代码行数:31,代码来源:bpgsql.py


示例5: write

def write(handle, devnumber, data):
	"""Writes some data to the receiver, addressed to a certain device.

	:param handle: an open UR handle.
	:param devnumber: attached device number.
	:param data: data to send, up to 5 bytes.

	The first two (required) bytes of data must be the SubId and address.

	:raises NoReceiver: if the receiver is no longer available, i.e. has
	been physically removed from the machine, or the kernel driver has been
	unloaded. The handle will be closed automatically.
	"""
	# the data is padded to either 5 or 18 bytes
	if len(data) > _SHORT_MESSAGE_SIZE - 2 or data[:1] == b'\x82':
		wdata = _pack(b'!BB18s', 0x11, devnumber, data)
	else:
		wdata = _pack(b'!BB5s', 0x10, devnumber, data)
	if _log.isEnabledFor(_DEBUG):
		_log.debug("(%s) <= w[%02X %02X %s %s]", handle, ord(wdata[:1]), devnumber, _strhex(wdata[2:4]), _strhex(wdata[4:]))

	try:
		_hid.write(int(handle), wdata)
	except Exception as reason:
		_log.error("write failed, assuming handle %r no longer available", handle)
		close(handle)
		raise NoReceiver(reason=reason)
开发者ID:Nek-,项目名称:Solaar,代码行数:27,代码来源:base.py


示例6: libuuid_generate_random

def libuuid_generate_random():
    """Generate a UUID with libuuid using a high-quality source of randomness.
    This will raise an exception if libuuid is not available.
    """
    buf = _pack(">16s","")
    out = _pack(">37s","")
    _libuuid.call("uuid_generate_random",buf)
    _libuuid.call("uuid_unparse",buf,out)
    return _unpack(">36sB",out)[0]
开发者ID:PauloJava2016,项目名称:Solfege,代码行数:9,代码来源:uuid.py


示例7: libuuid_generate_time

def libuuid_generate_time():
    """Generate a UUID with libuuid by mixing time and MAC address.
    This will raise an exception if libuuid is not available.
    """
    buf = _pack(">16s","")
    out = _pack(">37s","")
    _libuuid.call("uuid_generate_time",buf)
    _libuuid.call("uuid_unparse",buf,out)
    return _unpack(">36sB",out)[0]
开发者ID:PauloJava2016,项目名称:Solfege,代码行数:9,代码来源:uuid.py


示例8: libuuid_generate

def libuuid_generate():
    """Generate a UUID with libuuid using the best available method.
    This will raise an exception if libuuid is not available.
    """
    buf = _pack(">16s","")
    out = _pack(">37s","")
    _libuuid.call("uuid_generate",buf)
    _libuuid.call("uuid_unparse",buf,out)
    return _unpack(">36sB",out)[0]
开发者ID:PauloJava2016,项目名称:Solfege,代码行数:9,代码来源:uuid.py


示例9: a2s_rules

def a2s_rules(server_addr, timeout=2, challenge=0):
    """Get rules from server

    :param server_addr: (ip, port) for the server
    :type  server_addr: tuple
    :param timeout: (optional) timeout in seconds
    :type  timeout: float
    :param challenge: (optional) challenge number
    :type  challenge: int
    :raises: :class:`RuntimeError`, :class:`socket.timeout`
    :returns: a list of players
    :rtype: :class:`list`
    """
    ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ss.connect(server_addr)
    ss.settimeout(timeout)

    # request challenge number
    if challenge in (-1, 0):
        ss.send(_pack('<lci', -1, b'V', challenge))
        try:
            _, header, challenge = _unpack_from('<lcl', ss.recv(512))
        except:
            ss.close()
            raise

        if header != b'A':
            raise RuntimeError("Unexpected challenge response")

    # request player info
    ss.send(_pack('<lci', -1, b'V', challenge))

    try:
        data = StructReader(_handle_a2s_response(ss))
    finally:
        ss.close()

    header, num_rules = data.unpack('<4xcH')

    if header != b'E':
        raise RuntimeError("Invalid reponse header - %s" % repr(header))

    rules = {}

    while len(rules) != num_rules:
        name = data.read_cstring()
        value = data.read_cstring()

        if _re_match(r'^\-?[0-9]+$', value):
            value = int(value)
        elif _re_match(r'^\-?[0-9]+\.[0-9]+$', value):
            value = float(value)

        rules[name] = value

    return rules
开发者ID:philippj,项目名称:steam,代码行数:56,代码来源:game_servers.py


示例10: _makeapev2tag

def _makeapev2tag(apeitems):
    '''Construct an APE tag string from a dict of ApeItems'''
    apeentries = [item.maketag() for item in apeitems.itervalues()]
    apeentries.sort(_sortapeitems)
    apesize = _pack("<i",reduce(_apelengthreduce, apeentries, 32))
    numitems = _pack("<i",len(apeentries))
    headerfooter = _apepreamble + apesize + numitems
    apeentries.insert(0, headerfooter + '\0' + _apeheaderflags + "\x00" * 8)
    apeentries.append(headerfooter + '\0' + _apefooterflags + "\x00" * 8)
    return "".join(apeentries)
开发者ID:wzssyqa,项目名称:pythonkit,代码行数:10,代码来源:ApeTag.py


示例11: _inet_pton_af_inet

def _inet_pton_af_inet(ip_string):
    """
    Convert an IP address in string format (123.45.67.89) to the 32-bit packed
    binary format used in low-level network functions. Differs from inet_aton
    by only support decimal octets. Using octal or hexadecimal values will
    raise a ValueError exception.
    """
    #TODO: optimise this ... use inet_aton with mods if available ...
    if hasattr(ip_string, 'split'):
        invalid_addr = ValueError('illegal IP address string %r' % ip_string)
        #   Support for hexadecimal and octal octets.
        tokens = ip_string.split('.')

        #   Pack octets.
        if len(tokens) == 4:
            words = []
            for token in tokens:
                if token.startswith('0x') or \
                  (token.startswith('0') and len(token) > 1):
                    raise invalid_addr
                try:
                    octet = int(token)
                except ValueError:
                    raise invalid_addr

                if (octet >> 8) != 0:
                    raise invalid_addr
                words.append(_pack('B', octet))
            return _bytes_join(words)
        else:
            raise invalid_addr

    raise ValueError('argument should be a string, not %s' % type(ip_string))
开发者ID:0day1day,项目名称:golismero,代码行数:33,代码来源:fbsocket.py


示例12: _extranonce

def _extranonce(tmpl, workid):
	coinbase = tmpl.cbtxn.data
	if not workid:
		return coinbase
	extradata = _pack('<Q', workid)
	coinbase = _append_cb(tmpl, extradata)
	return coinbase
开发者ID:luke-jr,项目名称:python-blkmaker,代码行数:7,代码来源:blkmaker.py


示例13: get_mdata

def get_mdata(tmpl, usetime = None, out_expire = None, extranoncesz = sizeof_workid, can_roll_ntime = True):
	if usetime is None: usetime = _time()
	if not (True
		and time_left(tmpl, usetime)
		and (not tmpl.cbtxn is None)
		and _build_merkle_branches(tmpl)
	):
		return None
	
	if extranoncesz == sizeof_workid:
		# Avoid overlapping with blkmk_get_data use
		extranoncesz += 1
	
	cbuf = _pack('<I', tmpl.version)
	cbuf += tmpl.prevblk
	
	dummy = b'\0' * extranoncesz
	cbextranonceoffset = [None]
	cbtxn = _append_cb(tmpl, dummy, cbextranonceoffset)
	if cbtxn is None:
		return None
	cbuf += b'\0' * 0x20
	
	cbuf += _set_times(tmpl, usetime, out_expire, can_roll_ntime)
	cbuf += tmpl.diffbits
	
	return (cbuf, cbtxn, cbextranonceoffset[0], tmpl._mrklbranch)
开发者ID:luke-jr,项目名称:python-blkmaker,代码行数:27,代码来源:blkmaker.py


示例14: a2s_ping

def a2s_ping(server_addr, timeout=2):
    """Ping a server

    .. warning::
        This method for pinging is considered deprecated and may not work on certian servers.
        Use :func:`.a2s_info` instead.

    :param server_addr: (ip, port) for the server
    :type  server_addr: tuple
    :param timeout: (optional) timeout in seconds
    :type  timeout: float
    :raises: :class:`RuntimeError`, :class:`socket.timeout`
    :returns: ping response in milliseconds or `None` for timeout
    :rtype: :class:`float`
    """
    ss = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ss.connect(server_addr)
    ss.settimeout(timeout)

    ss.send(_pack('<lc', -1, b'i'))
    start = _time()

    try:
        data = _handle_a2s_response(ss)
    finally:
        ss.close()

    ping = max(0.0, _time() - start) * 1000

    if data[4:5] == b'j':
        return ping
开发者ID:philippj,项目名称:steam,代码行数:31,代码来源:game_servers.py


示例15: get_feature_report

def get_feature_report(device_handle, bytes_count, report_number=None):
	out_buffer = _C.create_string_buffer('\x00' * (bytes_count + 2))
	if report_number is not None:
		out_buffer[0] = _pack(b'!B', report_number)
	bytes_read = _native.hid_get_feature_report(device_handle, out_buffer, bytes_count)
	if bytes_read > -1:
		return out_buffer[:bytes_read]
开发者ID:bkidney,项目名称:freebsd-ports,代码行数:7,代码来源:hidapi.py


示例16: inet_ntop

def inet_ntop(af, packed_ip):
    """Convert an packed IP address of the given family to string format."""
    if af == AF_INET:
        #   IPv4.
        return inet_ntoa(packed_ip)
    elif af == AF_INET6:
        #   IPv6.
        if len(packed_ip) != 16 or not hasattr(packed_ip, 'split'):
            raise ValueError('invalid length of packed IP address string')

        tokens = ['%x' % i for i in _unpack('>8H', packed_ip)]

        #   Convert packed address to an integer value.
        words = list(_unpack('>8H', packed_ip))
        int_val = 0
        for i, num in enumerate(reversed(words)):
            word = num
            word = word << 16 * i
            int_val = int_val | word

        if 0xffff < int_val <= 0xffffffff or int_val >> 32 == 0xffff:
            #   IPv4 compatible / mapped IPv6.
            packed_ipv4 = _pack('>2H', *[int(i, 16) for i in tokens[-2:]])
            ipv4_str = inet_ntoa(packed_ipv4)
            tokens = tokens[0:-2] + [ipv4_str]

        return ':'.join(_compact_ipv6_tokens(tokens))
    else:
        raise ValueError('unknown address family %d' % af)
开发者ID:0day1day,项目名称:golismero,代码行数:29,代码来源:fbsocket.py


示例17: _get_random_bytes

def _get_random_bytes(n):
    reader = _get_random_reader()
    buf = ''
    if reader:
        loose_counter = 0
        while len(buf) != n:
            buf += reader(n)

            if loose_counter > 10:
                break
            loose_counter += 1
    d = n-len(buf)

    if d>0:
        buf += '\0'*d

    if n==16:
        fmt = _fmt_16

    elif n==6:
        fmt = _fmt_6

    elif n==2:
        fmt = _fmt_2

    else:
        fmt = ">%sB" % n
    return _pack(fmt,*tuple(map(_randomize_byte,_unpack(fmt,buf))))
开发者ID:RannyeriDev,项目名称:Solfege,代码行数:28,代码来源:uuid.py


示例18: code

def code(v, k):
    """
    TEA coder encrypt 64 bits value, by 128 bits key,
    QQ do 16 round TEA.
    To see:
    http://www.ftp.cl.cam.ac.uk/ftp/papers/djw-rmn/djw-rmn-tea.html .

    TEA 加密,  64比特明码, 128比特密钥, qq的TEA算法使用16轮迭代
    具体参看
    http://www.ftp.cl.cam.ac.uk/ftp/papers/djw-rmn/djw-rmn-tea.html
    >>> c = code('abcdefgh', 'aaaabbbbccccdddd')
    >>> b2a_hex(c)
    'a557272c538d3e96'
    """
    n=16  #qq use 16
    delta = 0x9e3779b9
    k = _unpack('>LLLL', k[0:16])
    y, z = _unpack('>LL', v[0:8])
    s = 0
    for i in range(n):
        s += delta
        y += (op &(z<<4))+ k[0] ^ z+ s ^ (op&(z>>5)) + k[1] ;
        y &= op
        z += (op &(y<<4))+ k[2] ^ y+ s ^ (op&(y>>5)) + k[3] ;
        z &= op
    r = _pack('>LL',y,z)
    return r
开发者ID:eignil,项目名称:qqloginjs,代码行数:27,代码来源:tea.py


示例19: decipher

def decipher(v, k):
    """
    TEA decipher, decrypt  64bits value with 128 bits key.
    TEA 解密程序, 用128比特密钥, 解密64比特值

    it's the inverse function of TEA encrypt.
    他是TEA加密函数的反函数.

    >>> c = code('abcdefgh', 'aaaabbbbccccdddd')
    >>> decipher( c, 'aaaabbbbccccdddd')
    'abcdefgh'
    """

    n = 16
    y, z = _unpack('>LL', v[0:8])
    a, b, c, d = _unpack('>LLLL', k[0:16])
    delta = 0x9E3779B9L;
    s = (delta << 4)&op
    for i in xrange(n):
        z -= ((y<<4)+c) ^ (y+s) ^ ((y>>5) + d)
        z &= op
        y -= ((z<<4)+a) ^ (z+s) ^ ((z>>5) + b)
        y &= op
        s -= delta
        s &= op
    return _pack('>LL', y, z)
开发者ID:Javacym,项目名称:python-qq,代码行数:26,代码来源:tea.py


示例20: _sample_data

def _sample_data(tmpl, dataid):
	cbuf = _pack('<I', tmpl.version)
	cbuf += tmpl.prevblk
	
	cbtxndata = _extranonce(tmpl, dataid)
	if not cbtxndata:
		return None
	
	merkleroot = _build_merkle_root(tmpl, cbtxndata)
	if not merkleroot:
		return None
	cbuf += merkleroot
	
	cbuf += _pack('<I', tmpl.curtime)
	cbuf += tmpl.diffbits
	
	return cbuf
开发者ID:luke-jr,项目名称:python-blkmaker,代码行数:17,代码来源:blkmaker.py



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


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python struct._unpack函数代码示例发布时间:2022-05-27
下一篇:
Python struct._calcsize函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap