當前位置: 首頁>>代碼示例>>Python>>正文


Python struct.error方法代碼示例

本文整理匯總了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]) 
開發者ID:google,項目名稱:macops,代碼行數:18,代碼來源:systemconfig.py

示例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 
開發者ID:pywren,項目名稱:pywren-ibm-cloud,代碼行數:21,代碼來源:utils.py

示例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 
開發者ID:sharph,項目名稱:lifx-python,代碼行數:26,代碼來源:network.py

示例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 
開發者ID:war-and-code,項目名稱:jawfish,代碼行數:19,代碼來源:platform.py

示例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 
開發者ID:trelby,項目名稱:trelby,代碼行數:20,代碼來源:truetype.py

示例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 
開發者ID:LonamiWebs,項目名稱:Telethon,代碼行數:21,代碼來源:utils.py

示例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 
開發者ID:pytest-dev,項目名稱:py,代碼行數:19,代碼來源:test_terminalwriter.py

示例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 
開發者ID:cryptax,項目名稱:droidlysis,代碼行數:19,代碼來源:droidziprar.py

示例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 
開發者ID:Korving-F,項目名稱:ublox,代碼行數:22,代碼來源:ubx.py

示例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 
開發者ID:Korving-F,項目名稱:ublox,代碼行數:23,代碼來源:ubx.py

示例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) 
開發者ID:Korving-F,項目名稱:ublox,代碼行數:20,代碼來源:ubx.py

示例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) 
開發者ID:Korving-F,項目名稱:ublox,代碼行數:19,代碼來源:ubx.py

示例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) 
開發者ID:Korving-F,項目名稱:ublox,代碼行數:24,代碼來源:ubx.py

示例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") 
開發者ID:Frank-qlu,項目名稱:recruit,代碼行數:20,代碼來源:ipaddress.py

示例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
        ) 
開發者ID:LuciferJack,項目名稱:python-mysql-pool,代碼行數:27,代碼來源:protocol.py


注:本文中的struct.error方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。