def read_nonblocking(self, size=1, timeout=None):
"""This reads data from the file descriptor.
This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it.
The timeout parameter is ignored.
"""
try:
s = os.read(self.child_fd, size)
except OSError as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Empty string style platform.')
s = self._decoder.decode(s, final=False)
self._log(s, 'read')
return s
python类EIO的实例源码
def readline(self):
"""Read one line from the pseudoterminal, and return it as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
"""
try:
s = self.fileobj.readline()
except (OSError, IOError) as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOFError('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
self.flag_eof = True
raise EOFError('End Of File (EOF). Empty string style platform.')
return s
def test_listen_dep_ioerror_exception_after_atr(self, device):
atr_req = 'D400 30313233343536373839 00000000'
atr_res = 'D501 d0d1d2d3d4d5d6d7d8d9 0000000800'
device.chipset.transport.read.side_effect = [
ACK(), RSP('09 00'), # WriteRegister
ACK(), RSP('8D 05 11' + atr_req), # TgInitAsTarget
ACK(), RSP('91 00'), # TgResponseToInitiator
ACK(), IOError(errno.EIO, ""), # TgGetInitiatorCommand
]
target = nfc.clf.LocalTarget()
target.sensf_res = HEX("01 01fe010203040506 0000000000000000 0000")
target.sens_res = HEX("0101")
target.sel_res = HEX("40")
target.sdd_res = HEX("08010203")
target.atr_res = HEX(atr_res)
with pytest.raises(IOError):
device.listen_dep(target, 1.0)
assert device.chipset.transport.read.call_count == 8
def test_listen_dep_not_atr_and_then_ioerror(self, device):
atr_req = 'D4FF 30313233343536373839 00000000'
atr_res = 'D501 d0d1d2d3d4d5d6d7d8d9 0000000800'
device.chipset.transport.read.side_effect = [
ACK(), RSP('09 00'), # WriteRegister
ACK(), RSP('8D 05 11' + atr_req), # TgInitAsTarget
ACK(), IOError(errno.ETIMEDOUT, ""), # TgInitAsTarget
ACK(), IOError(errno.EIO, ""), # TgInitAsTarget
]
target = nfc.clf.LocalTarget()
target.sensf_res = HEX("01 01fe010203040506 0000000000000000 0000")
target.sens_res = HEX("0101")
target.sel_res = HEX("40")
target.sdd_res = HEX("08010203")
target.atr_res = HEX(atr_res)
with pytest.raises(IOError):
device.listen_dep(target, 1.0)
assert device.chipset.transport.read.call_count == 8
def test_listen_dep_ioerror_exception_after_atr(self, device):
atr_req = 'D400 30313233343536373839 00000000'
atr_res = 'D501 d0d1d2d3d4d5d6d7d8d9 0000000800'
device.chipset.transport.read.side_effect = [
ACK(), RSP('19'), # ResetMode
ACK(), RSP('09 00'), # WriteRegister
ACK(), RSP('33'), # RFConfiguration
ACK(), RSP('13'), # SetParameters
ACK(), RSP('09 00'), # WriteRegister
ACK(), RSP('8D 05 11' + atr_req), # TgInitAsTarget
ACK(), RSP('93 00'), # TgSetGeneralBytes
ACK(), IOError(errno.EIO, ""), # TgGetInitiatorCommand
]
target = nfc.clf.LocalTarget()
target.sensf_res = HEX("01 01fe010203040506 0000000000000000 0000")
target.sens_res = HEX("0101")
target.sel_res = HEX("40")
target.sdd_res = HEX("08010203")
target.atr_res = HEX(atr_res)
with pytest.raises(IOError):
device.listen_dep(target, 1.0)
assert device.chipset.transport.read.call_count == 16
def ccid_xfr_block(self, data, timeout=0.1):
"""Encapsulate host command *data* into an PC/SC Escape command to
send to the device and extract the chip response if received
within *timeout* seconds.
"""
frame = struct.pack("<BI5B", 0x6F, len(data), 0, 0, 0, 0, 0) + data
self.transport.write(bytearray(frame))
frame = self.transport.read(int(timeout * 1000))
if not frame or len(frame) < 10:
log.error("insufficient data for decoding ccid response")
raise IOError(errno.EIO, os.strerror(errno.EIO))
if frame[0] != 0x80:
log.error("expected a RDR_to_PC_DataBlock")
raise IOError(errno.EIO, os.strerror(errno.EIO))
if len(frame) != 10 + struct.unpack("<I", buffer(frame, 1, 4))[0]:
log.error("RDR_to_PC_DataBlock length mismatch")
raise IOError(errno.EIO, os.strerror(errno.EIO))
return frame[10:]
def command(self, cmd_code, cmd_data, timeout):
"""Send a host command and return the chip response.
"""
log.log(logging.DEBUG-1, self.CMD[cmd_code]+" "+hexlify(cmd_data))
frame = bytearray([0xD4, cmd_code]) + bytearray(cmd_data)
frame = bytearray([0xFF, 0x00, 0x00, 0x00, len(frame)]) + frame
frame = self.ccid_xfr_block(frame, timeout)
if not frame or len(frame) < 4:
log.error("insufficient data for decoding chip response")
raise IOError(errno.EIO, os.strerror(errno.EIO))
if not (frame[0] == 0xD5 and frame[1] == cmd_code + 1):
log.error("received invalid chip response")
raise IOError(errno.EIO, os.strerror(errno.EIO))
if not (frame[-2] == 0x90 and frame[-1] == 0x00):
log.error("received pseudo apdu with error status")
raise IOError(errno.EIO, os.strerror(errno.EIO))
return frame[2:-2]
def read(self, timeout=0):
if self.usb_inp is not None:
try:
ep_addr = self.usb_inp.getAddress()
frame = self.usb_dev.bulkRead(ep_addr, 300, timeout)
except libusb.USBErrorTimeout:
raise IOError(errno.ETIMEDOUT, os.strerror(errno.ETIMEDOUT))
except libusb.USBErrorNoDevice:
raise IOError(errno.ENODEV, os.strerror(errno.ENODEV))
except libusb.USBError as error:
log.error("%r", error)
raise IOError(errno.EIO, os.strerror(errno.EIO))
if len(frame) == 0:
log.error("bulk read returned zero data")
raise IOError(errno.EIO, os.strerror(errno.EIO))
frame = bytearray(frame)
log.log(logging.DEBUG-1, "<<< %s", hexlify(frame))
return frame
def __init__(self, chipset, logger):
self.chipset = chipset
self.log = logger
try:
chipset_communication = self.chipset.diagnose('line')
except Chipset.Error:
chipset_communication = False
if chipset_communication is False:
self.log.error("chipset communication test failed")
raise IOError(errno.EIO, os.strerror(errno.EIO))
# for line in self._print_ciu_register_page(0, 1, 2, 3):
# self.log.debug(line)
# for addr in range(0, 0x03FF, 16):
# xram = self.chipset.read_register(*range(addr, addr+16))
# xram = ' '.join(["%02X" % x for x in xram])
# self.log.debug("0x%04X: %s", addr, xram)
def read_nonblocking(self, size=1, timeout=None):
"""This reads data from the file descriptor.
This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it.
The timeout parameter is ignored.
"""
try:
s = os.read(self.child_fd, size)
except OSError as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Empty string style platform.')
s = self._decoder.decode(s, final=False)
self._log(s, 'read')
return s
def readline(self):
"""Read one line from the pseudoterminal, and return it as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
"""
try:
s = self.fileobj.readline()
except (OSError, IOError) as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOFError('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
self.flag_eof = True
raise EOFError('End Of File (EOF). Empty string style platform.')
return s
def command(self, cmd_code, cmd_data=None, timeout=100):
"""Send a chip command and return the chip response."""
cmd_name = self.CMD.get(cmd_code, "PN53x 0x{0:02X}".format(cmd_code))
log.debug("{0} called with timeout {1} ms".format(cmd_name, timeout))
if cmd_data is None: cmd_data = ""
frame = bytearray([0xD4, cmd_code]) + bytearray(cmd_data)
frame = bytearray([0xFF, 0x00, 0x00, 0x00, len(frame)]) + frame
frame = bytearray([0x6B, len(frame)] + 8 * [0x00]) + frame
self.transport.write(frame)
frame = self.transport.read(timeout)
if len(frame) < 14:
strerror = os.strerror(errno.EIO) + " - Received frame too short"
raise IOError(errno.EIO, strerror)
if frame[0] != 0x83:
strerror = os.strerror(errno.EIO) + " - Unexpected start of frame"
raise IOError(errno.EIO, strerror)
if frame[-2] == 0x63:
strerror = os.strerror(errno.EIO) + " - No response from PN53X"
raise IOError(errno.EIO, strerror)
return frame[12:-2]
def __init__(self, chipset):
self.chipset = chipset
# perform a communication line test
if self.chipset.diagnose("line", "nfcpy") is not True:
raise IOError(errno.EIO, os.strerror(errno.EIO))
self._vendor_name = "NXP"
self._device_name = self.chipset.ic
RWT_WTX = {'PN531': (14, 7), "PN532": (14, 7), "PN533": (8, 1)}
rwt, wtx = RWT_WTX[self.chipset.ic]
# set ATR_RES timeout: 102.4 ms, non-DEP: 51.2 ms)
atr_res_to = 11 # T = 100 * 2^(x-1) s
non_dep_to = 10 # T = 100 * 2^(x-1) s
log.debug("ATR_RES timeout: {0:7.1f} ms".format(0.1*2**(atr_res_to-1)))
log.debug("non-DEP timeout: {0:7.1f} ms".format(0.1*2**(non_dep_to-1)))
atr_res_to = chr(atr_res_to); non_dep_to = chr(non_dep_to)
self.chipset.rf_configuration(0x02, chr(11) + atr_res_to + non_dep_to)
# retries for ATR_REQ, PSL_REQ, target activation
log.debug("set retries: ATR_REQ=2 PSL_REQ=1 PassiveTarget=3")
self.chipset.rf_configuration(0x05, "\x02\x01\x03")
def command(self, *cmd):
"""
Sends a command or sequence of commands through to the I²C address
- maximum allowed is 32 bytes in one go.
:param cmd: a spread of commands.
:type cmd: int
:raises luma.core.error.DeviceNotFoundError: I2C device could not be found.
"""
assert(len(cmd) <= 32)
try:
self._bus.write_i2c_block_data(self._addr, self._cmd_mode,
list(cmd))
except (IOError, OSError) as e:
if e.errno in [errno.EREMOTEIO, errno.EIO]:
# I/O error
raise luma.core.error.DeviceNotFoundError(
'I2C device not found on address: 0x{0:02X}'.format(self._addr))
else: # pragma: no cover
raise
def test_i2c_command_device_not_found_error():
errorbus = Mock(unsafe=True)
address = 0x71
cmds = [3, 1, 4, 2]
expected_error = OSError()
try:
for error_code in [errno.EREMOTEIO, errno.EIO]:
expected_error.errno = error_code
errorbus.write_i2c_block_data.side_effect = expected_error
serial = i2c(bus=errorbus, address=address)
with pytest.raises(luma.core.error.DeviceNotFoundError) as ex:
serial.command(*cmds)
assert str(ex.value) == 'I2C device not found on address: 0x{0:02X}'.format(
address)
except AttributeError as e:
# osx
pytest.skip(str(e))
def read_nonblocking(self, size=1, timeout=None):
"""This reads data from the file descriptor.
This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it.
The timeout parameter is ignored.
"""
try:
s = os.read(self.child_fd, size)
except OSError as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Empty string style platform.')
s = self._decoder.decode(s, final=False)
self._log(s, 'read')
return s
def readline(self):
"""Read one line from the pseudoterminal, and return it as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
"""
try:
s = self.fileobj.readline()
except (OSError, IOError) as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOFError('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
self.flag_eof = True
raise EOFError('End Of File (EOF). Empty string style platform.')
return s
def read_nonblocking(self, size=1, timeout=None):
"""This reads data from the file descriptor.
This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it.
The timeout parameter is ignored.
"""
try:
s = os.read(self.child_fd, size)
except OSError as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Empty string style platform.')
s = self._decoder.decode(s, final=False)
self._log(s, 'read')
return s
def readline(self):
"""Read one line from the pseudoterminal, and return it as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
"""
try:
s = self.fileobj.readline()
except (OSError, IOError) as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOFError('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
self.flag_eof = True
raise EOFError('End Of File (EOF). Empty string style platform.')
return s
def set_tc_from_file(logger, config_file_path, is_overwrite):
return_code = 0
loader = TcConfigLoader(logger)
loader.is_overwrite = is_overwrite
try:
loader.load_tcconfig(config_file_path)
except IOError as e:
logger.error("{:s}: {}".format(e.__class__.__name__, e))
return errno.EIO
for tcconfig_command in loader.get_tcconfig_command_list():
return_code |= subprocrunner.SubprocessRunner(
tcconfig_command).run()
return return_code
def read_nonblocking(self, size=1, timeout=None):
"""This reads data from the file descriptor.
This is a simple implementation suitable for a regular file. Subclasses using ptys or pipes should override it.
The timeout parameter is ignored.
"""
try:
s = os.read(self.child_fd, size)
except OSError as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF
self.flag_eof = True
raise EOF('End Of File (EOF). Empty string style platform.')
s = self._decoder.decode(s, final=False)
self._log(s, 'read')
return s
def readline(self):
"""Read one line from the pseudoterminal, and return it as unicode.
Can block if there is nothing to read. Raises :exc:`EOFError` if the
terminal was closed.
"""
try:
s = self.fileobj.readline()
except (OSError, IOError) as err:
if err.args[0] == errno.EIO:
# Linux-style EOF
self.flag_eof = True
raise EOFError('End Of File (EOF). Exception style platform.')
raise
if s == b'':
# BSD-style EOF (also appears to work on recent Solaris (OpenIndiana))
self.flag_eof = True
raise EOFError('End Of File (EOF). Empty string style platform.')
return s
def __enter__(self):
"""
supports use of the 'with' clause. You can use the expression:
with myobj as fp:
# write and/or read content here
"""
# Open our file and return a pointer to it
if self.open():
return self
# Throw an exception
raise IOError(errno.EIO, 'Could not open NNTPContent', self.path())
test_libevreactor.py 文件源码
项目:deb-python-cassandra-driver
作者: openstack
项目源码
文件源码
阅读 28
收藏 0
点赞 0
评论 0
def test_socket_error_on_write(self, *args):
c = self.make_connection()
# make the OptionsMessage write fail
c._socket.send.side_effect = socket_error(errno.EIO, "bad stuff!")
c.handle_write(None, 0)
# make sure it errored correctly
self.assertTrue(c.is_defunct)
self.assertIsInstance(c.last_error, socket_error)
self.assertTrue(c.connected_event.is_set())
test_libevreactor.py 文件源码
项目:deb-python-cassandra-driver
作者: openstack
项目源码
文件源码
阅读 21
收藏 0
点赞 0
评论 0
def test_socket_error_on_read(self, *args):
c = self.make_connection()
# let it write the OptionsMessage
c.handle_write(None, 0)
# read in a SupportedMessage response
c._socket.recv.side_effect = socket_error(errno.EIO, "busy socket")
c.handle_read(None, 0)
# make sure it errored correctly
self.assertTrue(c.is_defunct)
self.assertIsInstance(c.last_error, socket_error)
self.assertTrue(c.connected_event.is_set())
test_asyncorereactor.py 文件源码
项目:deb-python-cassandra-driver
作者: openstack
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def test_socket_error_on_write(self, *args):
c = self.make_connection()
# make the OptionsMessage write fail
c.socket.send.side_effect = socket_error(errno.EIO, "bad stuff!")
c.handle_write()
# make sure it errored correctly
self.assertTrue(c.is_defunct)
self.assertIsInstance(c.last_error, socket_error)
self.assertTrue(c.connected_event.is_set())
test_asyncorereactor.py 文件源码
项目:deb-python-cassandra-driver
作者: openstack
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def test_socket_error_on_read(self, *args):
c = self.make_connection()
# let it write the OptionsMessage
c.handle_write()
# read in a SupportedMessage response
c.socket.recv.side_effect = socket_error(errno.EIO, "busy socket")
c.handle_read()
# make sure it errored correctly
self.assertTrue(c.is_defunct)
self.assertIsInstance(c.last_error, socket_error)
self.assertTrue(c.connected_event.is_set())
def _run(self):
self._begin()
while True:
event = None
try:
event = self._pop()
except OSError, e:
if e.errno == errno.EIO: # dropped SSH connection? start over
self._kill_ssh()
self._begin()
continue
except ConnectionClosed: # dropped SSH connection? start over
self._kill_ssh()
self._begin()
continue
try:
event = json.loads(event)
except Exception, e:
print 'GES WARNING: %s' % e
continue
if self.pipe:
self.pipe.put(event)
if self.mailbox:
try:
self.mailbox.put_gerrit_event(event)
except Exception, e:
if str(e).startswith('project not tracked by heimdall'):
pass
elif str(e).startswith('ignoring'):
pass
else:
print 'GES WARNING:', e
def _run(self):
self._begin()
while True:
event = None
try:
event = self._pop()
except OSError, e:
if e.errno == errno.EIO: # dropped SSH connection? start over
self._kill_ssh()
self._begin()
continue
except ConnectionClosed: # dropped SSH connection? start over
self._kill_ssh()
self._begin()
continue
try:
event = json.loads(event)
except Exception, e:
print 'GES WARNING: %s' % e
continue
if self.pipe:
self.pipe.put(event)
if self.mailbox:
try:
self.mailbox.put_gerrit_event(event)
except Exception, e:
if str(e).startswith('project not tracked by heimdall'):
pass
elif str(e).startswith('ignoring'):
pass
else:
print 'GES WARNING:', e
def _fatal_error(self, exc, message):
if isinstance(exc, OSError) and exc.errno == errno.EIO:
if self._loop.get_debug():
logger.debug("%r: %s", self, message, exc_info=True)
else:
self._loop.call_exception_handler({
'message': message,
'exception': exc,
'transport': self,
'protocol': self._protocol,
})
self._close(error=exc)