Python struct.error() Examples
The following are 30 code examples for showing how to use struct.error(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
struct
, or try the search function
.
Example 1
Project: macops Author: google File: systemconfig.py License: Apache License 2.0 | 6 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
Project: pywren-ibm-cloud Author: pywren File: utils.py License: 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 3
Project: lifx-python Author: sharph File: network.py License: 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 4
Project: jawfish Author: war-and-code File: platform.py License: 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 5
Project: trelby Author: trelby File: truetype.py License: 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 6
Project: Telethon Author: LonamiWebs File: utils.py License: 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 7
Project: py Author: pytest-dev File: test_terminalwriter.py License: 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 8
Project: droidlysis Author: cryptax File: droidziprar.py License: MIT License | 6 votes |
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
Example 9
Project: ublox Author: Korving-F File: ubx.py License: 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 10
Project: ublox Author: Korving-F File: ubx.py License: 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 11
Project: ublox Author: Korving-F File: ubx.py License: 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 12
Project: ublox Author: Korving-F File: ubx.py License: 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 13
Project: ublox Author: Korving-F File: ubx.py License: 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 14
Project: recruit Author: Frank-qlu File: ipaddress.py License: 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 15
Project: python-mysql-pool Author: LuciferJack File: protocol.py License: 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 16
Project: python-mysql-pool Author: LuciferJack File: protocol.py License: 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 17
Project: segpy Author: sixty-north File: packer.py License: 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 18
Project: jbox Author: jpush File: ipaddress.py License: 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 19
Project: jbox Author: jpush File: ipaddress.py License: 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 20
Project: pycomm3 Author: ottowayi File: clx_legacy.py License: 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 21
Project: pycomm3 Author: ottowayi File: clx_legacy.py License: 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 22
Project: spotlight_parser Author: ydkhatri File: spotlight_parser_python2.py License: 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 23
Project: spotlight_parser Author: ydkhatri File: spotlight_parser.py License: 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 24
Project: Faraday-Software Author: FaradayRF File: proxy.py License: 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 25
Project: macops Author: google File: systemconfig.py License: 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 26
Project: pywren-ibm-cloud Author: pywren File: utils.py License: Apache License 2.0 | 5 votes |
def readline(self): try: retval = self.sb.readline() except struct.error: raise EOFError() self.pos += len(retval) return retval
Example 27
Project: jawfish Author: war-and-code File: platform.py License: MIT License | 5 votes |
def _node(default=''): """ Helper to determine the node name of this machine. """ try: import socket except ImportError: # No sockets... return default try: return socket.gethostname() except socket.error: # Still not working... return default
Example 28
Project: jawfish Author: war-and-code File: platform.py License: MIT License | 5 votes |
def _syscmd_file(target,default=''): """ Interface to the system's file command. The function uses the -b option of the file command to have it omit the filename in its output. Follow the symlinks. It returns default in case the command should fail. """ if sys.platform in ('dos','win32','win16','os2'): # XXX Others too ? return default target = _follow_symlinks(target) try: proc = subprocess.Popen(['file', target], stdout=subprocess.PIPE, stderr=subprocess.STDOUT) except (AttributeError,os.error): return default output = proc.communicate()[0].decode('latin-1') rc = proc.wait() if not output or rc: return default else: return output ### Information about the used architecture # Default values for architecture; non-empty strings override the # defaults given as parameters
Example 29
Project: Telethon Author: LonamiWebs File: mtprotosender.py License: MIT License | 5 votes |
def disconnected(self): """ Future that resolves when the connection to Telegram ends, either by user action or in the background. Note that it may resolve in either a ``ConnectionError`` or any other unexpected error that could not be handled. """ return asyncio.shield(self._disconnected, loop=self._loop) # Private methods
Example 30
Project: Telethon Author: LonamiWebs File: mtprotosender.py License: MIT License | 5 votes |
def _disconnect(self, error=None): if self._connection is None: self._log.info('Not disconnecting (already have no connection)') return self._log.info('Disconnecting from %s...', self._connection) self._user_connected = False try: self._log.debug('Closing current connection...') await self._connection.disconnect() finally: self._log.debug('Cancelling %d pending message(s)...', len(self._pending_state)) for state in self._pending_state.values(): if error and not state.future.done(): state.future.set_exception(error) else: state.future.cancel() self._pending_state.clear() await helpers._cancel( self._log, send_loop_handle=self._send_loop_handle, recv_loop_handle=self._recv_loop_handle ) self._log.info('Disconnection from %s complete!', self._connection) self._connection = None if self._disconnected and not self._disconnected.done(): if error: self._disconnected.set_exception(error) else: self._disconnected.set_result(None)