本文整理汇总了Python中struct._pack函数的典型用法代码示例。如果您正苦于以下问题:Python _pack函数的具体用法?Python _pack怎么用?Python _pack使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了_pack函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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
示例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
示例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)
示例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)
示例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)
示例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]
示例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]
示例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]
示例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
示例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)
示例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))
示例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
示例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)
示例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
示例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]