本文整理汇总了Python中struct.error方法的典型用法代码示例。如果您正苦于以下问题:Python struct.error方法的具体用法?Python struct.error怎么用?Python struct.error使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类struct
的用法示例。
在下文中一共展示了struct.error方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _GetMACFromData
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def _GetMACFromData(data):
"""Unpacks and formats MAC address data.
Args:
data: buffer, usually an NSCFData object
Returns:
string containing the MAC address
Raises:
InterfaceError: if data can't be unpacked
"""
try:
unpacked = struct.unpack_from('BBBBBB', data)
except struct.error as e:
logging.error('Could not unpack MAC address data: %s', e)
raise InterfaceError(e)
return ':'.join(['{:02x}'.format(i) for i in unpacked])
示例2: readline
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def readline(self):
if self.eof:
raise EOFError()
if not self.first_byte and self.plusbytes != 0:
self.first_byte = self.sb.read(self.plusbytes)
if self.first_byte != b'\n':
logger.debug('Discarding first partial row')
self.sb._raw_stream.readline()
try:
retval = self.sb._raw_stream.readline()
except struct.error:
raise EOFError()
self.pos += len(retval)
if self.pos >= self.size:
self.eof = True
return retval
示例3: recvpacket
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def recvpacket(timeout = None):
global connection
if connection is None:
connect()
#connection.settimeout(timeout)
#try:
# lengthdatum, addr = connection.recvfrom(2)
#except socket.timeout:
# return None
#connection.settimeout(None)
#try:
# (length, ) = struct.unpack('<H', lengthdatum)
#except struct.error:
# connect()
# return None
#data, addr = connection.recvfrom(length - 2)
try:
data, addr = connection.recvfrom(1024)
except socket.timeout:
return None
packet = packetcodec.decode_packet(data)
if debug:
print('recvpacket(): ', packet)
return packet
示例4: _syscmd_uname
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def _syscmd_uname(option,default=''):
""" Interface to the system's uname command.
"""
if sys.platform in ('dos','win32','win16','os2'):
# XXX Others too ?
return default
try:
f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
except (AttributeError,os.error):
return default
output = f.read().strip()
rc = f.close()
if not output or rc:
return default
else:
return output
示例5: __init__
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def __init__(self, s):
# is this a valid font
self.ok = False
# parse functions for tables, and a flag for whether each has been
# parsed successfully
self.parseFuncs = {
"head" : [self.parseHead, False],
"name" : [self.parseName, False],
"OS/2" : [self.parseOS2, False]
}
try:
self.parse(s)
except (struct.error, ParseError), e:
self.error = e
return
示例6: resolve_inline_message_id
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def resolve_inline_message_id(inline_msg_id):
"""
Resolves an inline message ID. Returns a tuple of
``(message id, peer, dc id, access hash)``
The ``peer`` may either be a :tl:`PeerUser` referencing
the user who sent the message via the bot in a private
conversation or small group chat, or a :tl:`PeerChannel`
if the message was sent in a channel.
The ``access_hash`` does not have any use yet.
"""
try:
dc_id, message_id, pid, access_hash = \
struct.unpack('<iiiq', _decode_telegram_base64(inline_msg_id))
peer = types.PeerChannel(-pid) if pid < 0 else types.PeerUser(pid)
return message_id, peer, dc_id, access_hash
except (struct.error, TypeError):
return None, None, None, None
示例7: test_getdimensions
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def test_getdimensions(monkeypatch):
if sys.version_info >= (3, 3):
import shutil
Size = namedtuple('Size', 'lines columns')
monkeypatch.setattr(shutil, 'get_terminal_size', lambda: Size(60, 100))
assert terminalwriter._getdimensions() == (60, 100)
else:
fcntl = py.test.importorskip("fcntl")
import struct
l = []
monkeypatch.setattr(fcntl, 'ioctl', lambda *args: l.append(args))
try:
terminalwriter._getdimensions()
except (TypeError, struct.error):
pass
assert len(l) == 1
assert l[0][0] == 1
示例8: open
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def open(self, filename):
try:
if self.zipmode:
if self.verbose:
print( "Opening Zip archive "+filename)
self.handle = zipfile.ZipFile(filename, 'r')
else:
if self.verbose:
print( "Opening Rar archive "+filename)
self.handle = rarfile.RarFile(filename, 'r')
except (struct.error, zipfile.BadZipfile, zipfile.LargeZipFile, IOError) as e:
if self.verbose:
print( "Exception caught in ZipFile: %s" % (repr(e)))
self.handle = None
return self.handle
示例9: __ubx_NAV_POSLLH
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def __ubx_NAV_POSLLH(self, dev):
payload = dev.read(size=30)
payload_cpy = payload
if self.__validate_checksum(1, 2, payload, dev):
try:
payload_cpy = payload_cpy[2:]
# Remove padding (=) introduced by struct for processor optimization
self.iTOW, self.lon, self.lat, self.height, self.hMSL, self.hAcc, self.vAcc = struct.unpack('=LllllLL', payload_cpy)
self.ubx_class = '01'
self.ubx_id = '02'
except struct.error:
print("{} {}".format(sys.exc_info()[0], sys.exc_info()[1]))
# time_of_week in ms / Dilution of Precision
# DOP is Dimensionless / scaled by factor 100
# Geometric / Position / Time / Vertical / Horizontal / Northing / Easting
示例10: __ubx_NAV_DOP
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def __ubx_NAV_DOP(self, dev):
payload = dev.read(size=20)
payload_cpy = payload
if self.__validate_checksum(1, 4, payload, dev):
try:
payload_cpy = payload_cpy[2:]
self.iTOW, self.gDOP, self.pDOP, self.tDOP, self.vDOP, self.hDOP, self.nDOP, self.eDOP = struct.unpack('=L7H', payload_cpy)
self.ubx_class = '01'
self.ubx_id = '04'
except struct.error:
print("{} {}".format(sys.exc_info()[0], sys.exc_info()[1]))
# Time_of_week in ms / Fractional time_of_week ns / Week number
# GPS Fix (6 valid types depending on status) / Fix status flags (4 types)
# ECEF X cm / ECEF Y cm / ECEF Z cm / Position Accuracy cm
# ECEF-Velocity X cm/s / ECEF-Velocity Y cm/s / ECEF-Velocity Z cm/s
# Speed Accuracy cm/s / Position DOP (scale 0.01)
# reserved / number of SV's used / reserved
示例11: __ubx_NAV_PVT
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def __ubx_NAV_PVT(self, dev):
payload = dev.read(size=94)
payload_cpy = payload
if(self.__validate_checksum(1, 7, payload, dev)):
try:
payload_cpy = payload[2:]
self.iTOW, self.year, self.month, self.day, self.hour, self.minute, self.second, self.valid, self.tAcc, self.nano, self.fixType, self.flags, self.flags2, self.numSV, self.lon, self.lat, self.height, self.hMSL, self.hAcc, self.vAcc, self.velN, self.velE, self.velD, self.gSpeed, self.headMot, self.sAcc, self.headAcc, self.pDOP, reserved11, reserved12, reserved13, reserved14, reserved15, reserved16, self.headVeh, self.magDec, self.magAcc = struct.unpack('=LH5BBLlB2BB4l2L5lLLH6BlhH', payload_cpy)
self.ubx_class = '01'
self.ubx_id = '07'
except struct.error:
print("{} {}".format(sys.exc_info()[0], sys.exc_info()[1]))
## UBX-ACK 0x05 ##
# UBX-ACK-ACK (0x05 0x01)
示例12: __ubx_ACK_ACK
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def __ubx_ACK_ACK(self, dev):
payload = dev.read(size=4)
payload_cpy = payload
if(self.__validate_checksum(5, 1, payload, dev)):
try:
payload_cpy = payload_cpy[2:]
self.clsID, self.msgID = struct.unpack('=BB', payload_cpy)
self.clsID, self.msgID = hex(self.clsID), hex(self.msgID)
self.ubx_class = '05'
self.ubx_id = '01'
except struct.error:
print("{} {}".format(sys.exc_info()[0], sys.exc_info()[1]))
# UBX-ACK-NAK (0x05 0x00)
示例13: __ubx_CFG_PRT
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def __ubx_CFG_PRT(self, rate):
header, ubx_class, ubx_id, length, uart_port = 46434, 6, 0, 20, 1
rate = hex(rate)
rate = rate[2:]
while(len(rate) < 8):
rate = '0' + rate
rate1, rate2, rate3, rate4 = int(rate[-2:], 16), int(rate[-4:-2], 16), int(rate[2:4], 16), int(rate[:2], 16)
payload = [length, 0, uart_port, 0, 0, 0, 208, 8, 0, 0, rate1, rate2, rate3, rate4, 7, 0, 3, 0, 0, 0, 0, 0]
checksum = self.__calc_checksum(ubx_class, ubx_id, payload)
payload = payload + checksum
try:
self.msg = struct.pack('>H26B', header, ubx_class, ubx_id, *payload)
self.ubx_class = '06'
self.ubx_id = '00'
except struct.error:
print("{} {}".format(sys.exc_info()[0], sys.exc_info()[1]))
# UBX-CFG-MSG (0x06 0x01)
示例14: v4_int_to_packed
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def v4_int_to_packed(address):
"""Represent an address as 4 packed bytes in network (big-endian) order.
Args:
address: An integer representation of an IPv4 IP address.
Returns:
The integer address packed as 4 bytes in network (big-endian) order.
Raises:
ValueError: If the integer is negative or too large to be an
IPv4 IP address.
"""
try:
return _compat_to_bytes(address, 4, 'big')
except (struct.error, OverflowError):
raise ValueError("Address negative or too large for IPv4")
示例15: parse_column
# 需要导入模块: import struct [as 别名]
# 或者: from struct import error [as 别名]
def parse_column(self, packet, charset='utf-8'):
"""Parse a MySQL column-packet"""
(packet, _) = utils.read_lc_string(packet[4:]) # catalog
(packet, _) = utils.read_lc_string(packet) # db
(packet, _) = utils.read_lc_string(packet) # table
(packet, _) = utils.read_lc_string(packet) # org_table
(packet, name) = utils.read_lc_string(packet) # name
(packet, _) = utils.read_lc_string(packet) # org_name
try:
(_, _, field_type,
flags, _) = struct_unpack('<xHIBHBxx', packet)
except struct.error:
raise errors.InterfaceError("Failed parsing column information")
return (
name.decode(charset),
field_type,
None, # display_size
None, # internal_size
None, # precision
None, # scale
~flags & FieldFlag.NOT_NULL, # null_ok
flags, # MySQL specific
)