Python struct.error() Examples
The following are 30
code examples of struct.error().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
struct
, or try the search function
.
Example #1
Source File: systemconfig.py From macops with Apache License 2.0 | 7 votes |
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])
Example #2
Source File: utils.py From Telethon with MIT License | 6 votes |
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
Example #3
Source File: truetype.py From trelby with GNU General Public License v2.0 | 6 votes |
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
Example #4
Source File: network.py From lifx-python with GNU Affero General Public License v3.0 | 6 votes |
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
Example #5
Source File: utils.py From pywren-ibm-cloud with Apache License 2.0 | 6 votes |
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
Example #6
Source File: platform.py From jawfish with MIT License | 6 votes |
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
Example #7
Source File: spotlight_parser.py From spotlight_parser with GNU General Public License v3.0 | 6 votes |
def ParseIndexes(self, block, dictionary): data = block.data pos = 32 size = block.logical_size while pos < size: index = struct.unpack("<I", data[pos : pos+4])[0] pos += 4 index_size, bytes_moved = SpotlightStore.ReadVarSizeNum(data[pos:]) pos += bytes_moved padding = index_size % 4 pos += padding index_size = 4*int(index_size//4) ids = struct.unpack("<" + str(index_size//4) + "i", data[pos:pos + index_size]) pos += index_size # sanity check temp = dictionary.get(index, None) if temp != None: log.error("Error, category {} already exists!!".format(temp)) # end check dictionary[index] = ids
Example #8
Source File: proxy.py From Faraday-Software with GNU General Public License v3.0 | 6 votes |
def saveProxyLog(name, config): ''' Save proxy log database into a new file :param name: Name of file to save data into (should be .db) :param config: Proxy ConfigParser object from proxy.ini :return: None ''' log = config.get("DATABASE", "filename") oldpath = os.path.join(faradayHelper.userPath, 'lib', log) newpath = os.path.join(faradayHelper.userPath, 'lib', name) try: shutil.move(oldpath, newpath) sys.exit(0) except shutil.Error as e: logger.error(e) except IOError as e: logger.error(e)
Example #9
Source File: spotlight_parser_python2.py From spotlight_parser with GNU General Public License v3.0 | 6 votes |
def ParseIndexes(self, block, dictionary): data = block.data pos = 32 size = block.logical_size while pos < size: index = struct.unpack("<I", data[pos : pos+4])[0] pos += 4 index_size, bytes_moved = SpotlightStore.ReadVarSizeNum(data[pos:]) pos += bytes_moved padding = index_size % 4 pos += padding index_size = 4*int(index_size//4) ids = struct.unpack("<" + str(index_size//4) + "I", data[pos:pos + index_size]) pos += index_size # sanity check temp = dictionary.get(index, None) if temp != None: log.error("Error, category {} already exists!!".format(temp)) # end check dictionary[index] = ids
Example #10
Source File: protocol.py From python-mysql-pool with MIT License | 6 votes |
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 )
Example #11
Source File: test_terminalwriter.py From py with MIT License | 6 votes |
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
Example #12
Source File: ubx.py From ublox with MIT License | 6 votes |
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
Example #13
Source File: ubx.py From ublox with MIT License | 6 votes |
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)
Example #14
Source File: protocol.py From python-mysql-pool with MIT License | 6 votes |
def parse_eof(self, packet): """Parse a MySQL EOF-packet""" if packet[4] == 0: # EOF packet deprecation return self.parse_ok(packet) err_msg = "Failed parsing EOF packet." res = {} try: unpacked = struct_unpack('<xxxBBHH', packet) except struct.error: raise errors.InterfaceError(err_msg) if not (unpacked[1] == 254 and len(packet) <= 9): raise errors.InterfaceError(err_msg) res['warning_count'] = unpacked[2] res['status_flag'] = unpacked[3] return res
Example #15
Source File: packer.py From segpy with GNU Affero General Public License v3.0 | 6 votes |
def unpack(self, buffer): """Unpack a header into a header object. Overwrites any existing header field values with new values obtained from the buffer. Returns: The header object. """ try: values = self._structure.unpack(buffer) except struct.error as e: raise ValueError("Buffer of length {} too short" .format(len(buffer), str(e).capitalize())) from e else: return self._unpack(values)
Example #16
Source File: ipaddress.py From jbox with MIT License | 6 votes |
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")
Example #17
Source File: ipaddress.py From recruit with Apache License 2.0 | 6 votes |
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")
Example #18
Source File: ipaddress.py From jbox with MIT License | 6 votes |
def _parse_hextet(cls, hextet_str): """Convert an IPv6 hextet string into an integer. Args: hextet_str: A string, the number to parse. Returns: The hextet as an integer. Raises: ValueError: if the input isn't strictly a hex number from [0..FFFF]. """ # Whitelist the characters, since int() allows a lot of bizarre stuff. if not cls._HEX_DIGITS.issuperset(hextet_str): raise ValueError("Only hex digits permitted in %r" % hextet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(hextet_str) > 4: msg = "At most 4 characters permitted in %r" raise ValueError(msg % hextet_str) # Length check means we can skip checking the integer value return int(hextet_str, 16)
Example #19
Source File: clx_legacy.py From pycomm3 with MIT License | 6 votes |
def read_tag(self, *tags): """ read tag from a connected plc Possible combination can be passed to this method: - ('Counts') a single tag name - (['ControlWord']) a list with one tag or many - (['parts', 'ControlWord', 'Counts']) At the moment there is not a strong validation for the argument passed. The user should verify the correctness of the format passed. :return: None is returned in case of error otherwise the tag list is returned """ if not self._forward_open(): self.__log.warning("Target did not connected. read_tag will not be executed.") raise DataError("Target did not connected. read_tag will not be executed.") if len(tags) == 1: if isinstance(tags[0], (list, tuple, GeneratorType)): return self._read_tag_multi(tags[0]) else: return self._read_tag_single(tags[0]) else: return self._read_tag_multi(tags)
Example #20
Source File: clx_legacy.py From pycomm3 with MIT License | 6 votes |
def _parse_multiple_request_write(tags, reply): """ parse the message received from a multi request writ: For each tag parsed, the information extracted includes the tag name and the status of the writing. Those information are appended to the tag list as tuple :return: the tag list """ offset = 50 position = 50 try: number_of_service_replies = unpack_uint(reply[offset:offset + 2]) tag_list = [] for index in range(number_of_service_replies): position += 2 start = offset + unpack_uint(reply[position:position + 2]) general_status = unpack_usint(reply[start + 2:start + 3]) error = None if general_status == SUCCESS else get_service_status(general_status) tag_list.append(Tag(*tags[index], error)) return tag_list except Exception as e: raise DataError(e)
Example #21
Source File: ubx.py From ublox with MIT License | 6 votes |
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)
Example #22
Source File: ubx.py From ublox with MIT License | 6 votes |
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)
Example #23
Source File: ubx.py From ublox with MIT License | 6 votes |
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
Example #24
Source File: ipaddress.py From jbox with MIT License | 5 votes |
def _parse_octet(cls, octet_str): """Convert a decimal octet into an integer. Args: octet_str: A string, the number to parse. Returns: The octet as an integer. Raises: ValueError: if the octet isn't strictly a decimal from [0..255]. """ if not octet_str: raise ValueError("Empty octet not permitted") # Whitelist the characters, since int() allows a lot of bizarre stuff. if not cls._DECIMAL_DIGITS.issuperset(octet_str): msg = "Only decimal digits permitted in %r" raise ValueError(msg % octet_str) # We do the length check second, since the invalid character error # is likely to be more informative for the user if len(octet_str) > 3: msg = "At most 3 characters permitted in %r" raise ValueError(msg % octet_str) # Convert to integer (we know digits are legal) octet_int = int(octet_str, 10) # Any octets that look like they *might* be written in octal, # and which don't look exactly the same in both octal and # decimal are rejected as ambiguous if octet_int > 7 and octet_str[0] == '0': msg = "Ambiguous (octal/decimal) value in %r not permitted" raise ValueError(msg % octet_str) if octet_int > 255: raise ValueError("Octet %d (> 255) not permitted" % octet_int) return octet_int
Example #25
Source File: clx_legacy.py From pycomm3 with MIT License | 5 votes |
def _send(self, message): """ socket send :return: true if no error otherwise false """ try: if self.debug: self.__log.debug(print_bytes_msg(message, '>>> SEND >>>')) self._sock.send(message) except Exception as e: raise CommError(e)
Example #26
Source File: validate.py From NINJA-PingU with GNU General Public License v3.0 | 5 votes |
def dottedQuadToNum(ip): """ Convert decimal dotted quad string to long integer >>> int(dottedQuadToNum('1 ')) 1 >>> int(dottedQuadToNum(' 1.2')) 16777218 >>> int(dottedQuadToNum(' 1.2.3 ')) 16908291 >>> int(dottedQuadToNum('1.2.3.4')) 16909060 >>> dottedQuadToNum('1.2.3. 4') 16909060 >>> dottedQuadToNum('255.255.255.255') 4294967295L >>> dottedQuadToNum('255.255.255.256') Traceback (most recent call last): ValueError: Not a good dotted-quad IP: 255.255.255.256 """ # import here to avoid it when ip_addr values are not used import socket, struct try: return struct.unpack('!L', socket.inet_aton(ip.strip()))[0] except socket.error: # bug in inet_aton, corrected in Python 2.3 if ip.strip() == '255.255.255.255': return 0xFFFFFFFFL else: raise ValueError('Not a good dotted-quad IP: %s' % ip) return
Example #27
Source File: proxy.py From Faraday-Software with GNU General Public License v3.0 | 5 votes |
def closeConnection(conn, addr, faraday): # close the connection logger.info("Closing connection with {0} on {1}".format(addr[0], faraday)) time.sleep(0.01) # Need to give time for any TX to finish try: conn.close() except IOError as e: logger.error(e)
Example #28
Source File: ipaddress.py From jbox with MIT License | 5 votes |
def _compat_to_bytes(intval, length, endianess): assert isinstance(intval, _compat_int_types) assert endianess == 'big' if length == 4: if intval < 0 or intval >= 2 ** 32: raise struct.error("integer out of range for 'I' format code") return struct.pack(b'!I', intval) elif length == 16: if intval < 0 or intval >= 2 ** 128: raise struct.error("integer out of range for 'QQ' format code") return struct.pack(b'!QQ', intval >> 64, intval & 0xffffffffffffffff) else: raise NotImplementedError()
Example #29
Source File: systemconfig.py From macops with Apache License 2.0 | 5 votes |
def ConfigureSystemProxy(proxy=CORP_PROXY, enable=True): """Sets the system proxy to the specified value.""" scd_prefs = SCDynamicPreferences() if not scd_prefs.SetProxy(enable=enable, pac=proxy): logging.error('Could not change proxy settings.')
Example #30
Source File: proxy.py From Faraday-Software with GNU General Public License v3.0 | 5 votes |
def createPacket(data, size): # initialize temp variable list and packet temp = [] packet = '' # Pop off "size" bytes and append to temporary list i = 0 for i in range(size): try: a = data.popleft() temp.append(a) except IndexError: # simply an empty queue pass # Join list together and append two control bytes, convert to BASE64 try: # TODO: Use better method of MSP430 header allocation payload = ''.join(temp) preamble = struct.pack("BB", 0, 0) # Header for MSP430 firmware size = struct.pack("B", len(payload)) framedPayload = size + payload packet = (preamble + framedPayload).encode('base64', 'strict') # Proxy expects BASE64 except TypeError as e: logger.error(e) except struct.error as e: logger.warning(e) except UnicodeError as e: logger.error(e) except StandardError as e: logger.info("StandardError") logger.error(e) return packet