diff options
author | Chris Liechti <cliechti@gmx.net> | 2016-02-16 21:06:52 +0100 |
---|---|---|
committer | Chris Liechti <cliechti@gmx.net> | 2016-02-16 21:06:52 +0100 |
commit | 1f6643d843ee137a2839a65a2d33a75aab53008d (patch) | |
tree | 9988a11f2358a38ef2883d121ff28b498055c197 | |
parent | 984c5c5baf53b35504e1696d1d8428c3b83cf25b (diff) | |
download | pyserial-git-1f6643d843ee137a2839a65a2d33a75aab53008d.tar.gz |
style: replace % with format calls
-rw-r--r-- | serial/rfc2217.py | 103 | ||||
-rw-r--r-- | serial/serialwin32.py | 36 |
2 files changed, 73 insertions, 66 deletions
diff --git a/serial/rfc2217.py b/serial/rfc2217.py index 119f039..a9b285a 100644 --- a/serial/rfc2217.py +++ b/serial/rfc2217.py @@ -260,7 +260,7 @@ class TelnetOption(object): def __repr__(self): """String for debug outputs""" - return "%s:%s(%s)" % (self.name, self.active, self.state) + return "{o.name}:{o.active}({o.state})".format(o=self) def process_incoming(self, command): """\ @@ -284,7 +284,7 @@ class TelnetOption(object): elif self.state is REALLY_INACTIVE: self.connection.telnetSendOption(self.send_no, self.option) else: - raise ValueError('option in illegal state %r' % self) + raise ValueError('option in illegal state {!r}'.format(self)) elif command == self.ack_no: if self.state is REQUESTED: self.state = INACTIVE @@ -298,7 +298,7 @@ class TelnetOption(object): elif self.state is REALLY_INACTIVE: pass else: - raise ValueError('option in illegal state %r' % self) + raise ValueError('option in illegal state {!r}'.format(self)) class TelnetSubnegotiation(object): @@ -319,7 +319,7 @@ class TelnetSubnegotiation(object): def __repr__(self): """String for debug outputs.""" - return "%s:%s" % (self.name, self.state) + return "{sn.name}:{sn.state}".format(sn=self) def set(self, value): """\ @@ -331,7 +331,7 @@ class TelnetSubnegotiation(object): self.state = REQUESTED self.connection.rfc2217SendSubnegotiation(self.option, self.value) if self.connection.logger: - self.connection.logger.debug("SB Requesting %s -> %r" % (self.name, self.value)) + self.connection.logger.debug("SB Requesting {} -> {!r}".format(self.name, self.value)) def isReady(self): """\ @@ -339,7 +339,7 @@ class TelnetSubnegotiation(object): the change, raise a ValueError. """ if self.state == REALLY_INACTIVE: - raise ValueError("remote rejected value for option %r" % (self.name)) + raise ValueError("remote rejected value for option {!r}".format(self.name)) return self.state == ACTIVE # add property to have a similar interface as TelnetOption active = property(isReady) @@ -356,7 +356,7 @@ class TelnetSubnegotiation(object): if self.isReady(): break else: - raise SerialException("timeout while waiting for option %r" % (self.name)) + raise SerialException("timeout while waiting for option {!r}".format(self.name)) def checkAnswer(self, suboption): """\ @@ -369,7 +369,7 @@ class TelnetSubnegotiation(object): # error propagation done in isReady self.state = REALLY_INACTIVE if self.connection.logger: - self.connection.logger.debug("SB Answer %s -> %r -> %s" % (self.name, suboption, self.state)) + self.connection.logger.debug("SB Answer {} -> {!r} -> {}".format(self.name, suboption, self.state)) class Serial(SerialBase): @@ -401,7 +401,7 @@ class Serial(SerialBase): self._socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) except Exception as msg: self._socket = None - raise SerialException("Could not open port %s: %s" % (self.portstr, msg)) + raise SerialException("Could not open port {}: {}".format(self.portstr, msg)) self._socket.settimeout(5) # XXX good value? @@ -449,7 +449,7 @@ class Serial(SerialBase): self.is_open = True self._thread = threading.Thread(target=self._telnetReadLoop) self._thread.setDaemon(True) - self._thread.setName('pySerial RFC 2217 reader thread for %s' % (self._port,)) + self._thread.setName('pySerial RFC 2217 reader thread for {}'.format(self._port)) self._thread.start() try: # must clean-up if open fails @@ -464,9 +464,9 @@ class Serial(SerialBase): if sum(o.active for o in mandadory_options) == sum(o.state != INACTIVE for o in mandadory_options): break else: - raise SerialException("Remote does not seem to support RFC2217 or BINARY mode %r" % mandadory_options) + raise SerialException("Remote does not seem to support RFC2217 or BINARY mode {!r}".format(mandadory_options)) if self.logger: - self.logger.info("Negotiated options: %s" % self._telnet_options) + self.logger.info("Negotiated options: {}".format(self._telnet_options)) # fine, go on, set RFC 2271 specific things self._reconfigure_port() @@ -496,7 +496,7 @@ class Serial(SerialBase): # Setup the connection # to get good performance, all parameter changes are sent first... if not 0 < self._baudrate < 2 ** 32: - raise ValueError("invalid baudrate: %r" % (self._baudrate)) + raise ValueError("invalid baudrate: {!r}".format(self._baudrate)) self._rfc2217_port_settings['baudrate'].set(struct.pack(b'!I', self._baudrate)) self._rfc2217_port_settings['datasize'].set(struct.pack(b'!B', self._bytesize)) self._rfc2217_port_settings['parity'].set(struct.pack(b'!B', RFC2217_PARITY_MAP[self._parity])) @@ -505,16 +505,16 @@ class Serial(SerialBase): # and now wait until parameters are active items = self._rfc2217_port_settings.values() if self.logger: - self.logger.debug("Negotiating settings: %s" % (items,)) + self.logger.debug("Negotiating settings: {}".format(items)) timeout_time = time.time() + self._network_timeout while time.time() < timeout_time: time.sleep(0.05) # prevent 100% CPU load if sum(o.active for o in items) == len(items): break else: - raise SerialException("Remote does not accept parameter change (RFC2217): %r" % items) + raise SerialException("Remote does not accept parameter change (RFC2217): {!r}".format(items)) if self.logger: - self.logger.info("Negotiated settings: %s" % (items,)) + self.logger.info("Negotiated settings: {}".format(items)) if self._rtscts and self._xonxoff: raise ValueError('xonxoff and rtscts together are not supported') @@ -546,7 +546,10 @@ class Serial(SerialBase): """extract host and port from an URL string""" parts = urlparse.urlsplit(url) if parts.scheme != "rfc2217": - raise SerialException('expected a string in the form "rfc2217://<host>:<port>[?option[&option...]]": not starting with rfc2217:// (%r)' % (parts.scheme,)) + raise SerialException( + 'expected a string in the form ' + '"rfc2217://<host>:<port>[?option[&option...]]": ' + 'not starting with rfc2217:// ({!r})'.format(parts.scheme)) try: # process options now, directly altering self for option, values in urlparse.parse_qs(parts.query, True).items(): @@ -562,13 +565,15 @@ class Serial(SerialBase): elif option == 'timeout': self._network_timeout = float(values[0]) else: - raise ValueError('unknown option: %r' % (option,)) + raise ValueError('unknown option: {!r}'.format(option)) # get host and port host, port = parts.hostname, parts.port if not 0 <= port < 65536: raise ValueError("port not in range 0...65535") except ValueError as e: - raise SerialException('expected a string in the form "rfc2217://<host>:<port>[?option[&option...]]": %s' % e) + raise SerialException( + 'expected a string in the form ' + '"rfc2217://<host>:<port>[?option[&option...]]": {}'.format(e)) return (host, port) # - - - - - - - - - - - - - - - - - - - - - - - - @@ -610,7 +615,7 @@ class Serial(SerialBase): try: self._socket.sendall(to_bytes(data).replace(IAC, IAC_DOUBLED)) except socket.error as e: - raise SerialException("connection failed (socket error): %s" % (e,)) + raise SerialException("connection failed (socket error): {}".format(e)) return len(data) def reset_input_buffer(self): @@ -639,7 +644,7 @@ class Serial(SerialBase): if not self.is_open: raise portNotOpenError if self.logger: - self.logger.info('set BREAK to %s' % ('active' if self._break_state else 'inactive')) + self.logger.info('set BREAK to {}'.format('active' if self._break_state else 'inactive')) if self._break_state: self.rfc2217SetControl(SET_CONTROL_BREAK_ON) else: @@ -650,7 +655,7 @@ class Serial(SerialBase): if not self.is_open: raise portNotOpenError if self.logger: - self.logger.info('set RTS to %s' % ('active' if self._rts_state else 'inactive')) + self.logger.info('set RTS to {}'.format('active' if self._rts_state else 'inactive')) if self._rts_state: self.rfc2217SetControl(SET_CONTROL_RTS_ON) else: @@ -661,7 +666,7 @@ class Serial(SerialBase): if not self.is_open: raise portNotOpenError if self.logger: - self.logger.info('set DTR to %s' % ('active' if self._dtr_state else 'inactive')) + self.logger.info('set DTR to {}'.format('active' if self._dtr_state else 'inactive')) if self._dtr_state: self.rfc2217SetControl(SET_CONTROL_DTR_ON) else: @@ -715,7 +720,7 @@ class Serial(SerialBase): except socket.error as e: # connection fails -> terminate loop if self.logger: - self.logger.debug("socket error in reader thread: %s" % (e,)) + self.logger.debug("socket error in reader thread: {}".format(e)) break if not data: break # lost connection @@ -771,7 +776,7 @@ class Serial(SerialBase): """Process commands other than DO, DONT, WILL, WONT.""" # Currently none. RFC2217 only uses negotiation and subnegotiation. if self.logger: - self.logger.warning("ignoring Telnet command: %r" % (command,)) + self.logger.warning("ignoring Telnet command: {!r}".format(command)) def _telnetNegotiateOption(self, command, option): """Process incoming DO, DONT, WILL, WONT.""" @@ -790,7 +795,7 @@ class Serial(SerialBase): if command == WILL or command == DO: self.telnetSendOption((DONT if command == WILL else WONT), option) if self.logger: - self.logger.warning("rejected Telnet option: %r" % (option,)) + self.logger.warning("rejected Telnet option: {!r}".format(option)) def _telnetProcessSubnegotiation(self, suboption): """Process subnegotiation, the data between IAC SB and IAC SE.""" @@ -798,11 +803,11 @@ class Serial(SerialBase): if suboption[1:2] == SERVER_NOTIFY_LINESTATE and len(suboption) >= 3: self._linestate = ord(suboption[2:3]) # ensure it is a number if self.logger: - self.logger.info("NOTIFY_LINESTATE: %s" % self._linestate) + self.logger.info("NOTIFY_LINESTATE: {}".format(self._linestate)) elif suboption[1:2] == SERVER_NOTIFY_MODEMSTATE and len(suboption) >= 3: self._modemstate = ord(suboption[2:3]) # ensure it is a number if self.logger: - self.logger.info("NOTIFY_MODEMSTATE: %s" % self._modemstate) + self.logger.info("NOTIFY_MODEMSTATE: {}".format(self._modemstate)) # update time when we think that a poll would make sense self._modemstate_expires = time.time() + 0.3 elif suboption[1:2] == FLOWCONTROL_SUSPEND: @@ -817,10 +822,10 @@ class Serial(SerialBase): break else: if self.logger: - self.logger.warning("ignoring COM_PORT_OPTION: %r" % (suboption,)) + self.logger.warning("ignoring COM_PORT_OPTION: {!r}".format(suboption)) else: if self.logger: - self.logger.warning("ignoring subnegotiation: %r" % (suboption,)) + self.logger.warning("ignoring subnegotiation: {!r}".format(suboption)) # - outgoing telnet commands and options @@ -999,7 +1004,7 @@ class PortManager(object): SERVER_NOTIFY_MODEMSTATE, to_bytes([modemstate & self.modemstate_mask])) if self.logger: - self.logger.info("NOTIFY_MODEMSTATE: %s" % (modemstate,)) + self.logger.info("NOTIFY_MODEMSTATE: {}".format(modemstate)) # save last state, but forget about deltas. # otherwise it would also notify about changing deltas which is # probably not very useful @@ -1087,7 +1092,7 @@ class PortManager(object): """Process commands other than DO, DONT, WILL, WONT.""" # Currently none. RFC2217 only uses negotiation and subnegotiation. if self.logger: - self.logger.warning("ignoring Telnet command: %r" % (command,)) + self.logger.warning("ignoring Telnet command: {!r}".format(command)) def _telnetNegotiateOption(self, command, option): """Process incoming DO, DONT, WILL, WONT.""" @@ -1106,13 +1111,13 @@ class PortManager(object): if command == WILL or command == DO: self.telnetSendOption((DONT if command == WILL else WONT), option) if self.logger: - self.logger.warning("rejected Telnet option: %r" % (option,)) + self.logger.warning("rejected Telnet option: {!r}".format(option)) def _telnetProcessSubnegotiation(self, suboption): """Process subnegotiation, the data between IAC SB and IAC SE.""" if suboption[0:1] == COM_PORT_OPTION: if self.logger: - self.logger.debug('received COM_PORT_OPTION: %r' % (suboption,)) + self.logger.debug('received COM_PORT_OPTION: {!r}'.format(suboption)) if suboption[1:2] == SET_BAUDRATE: backup = self.serial.baudrate try: @@ -1121,11 +1126,11 @@ class PortManager(object): self.serial.baudrate = baudrate except ValueError as e: if self.logger: - self.logger.error("failed to set baud rate: %s" % (e,)) + self.logger.error("failed to set baud rate: {}".format(e)) self.serial.baudrate = backup else: if self.logger: - self.logger.info("%s baud rate: %s" % ('set' if baudrate else 'get', self.serial.baudrate)) + self.logger.info("{} baud rate: {}".format('set' if baudrate else 'get', self.serial.baudrate)) self.rfc2217SendSubnegotiation(SERVER_SET_BAUDRATE, struct.pack(b"!I", self.serial.baudrate)) elif suboption[1:2] == SET_DATASIZE: backup = self.serial.bytesize @@ -1135,11 +1140,11 @@ class PortManager(object): self.serial.bytesize = datasize except ValueError as e: if self.logger: - self.logger.error("failed to set data size: %s" % (e,)) + self.logger.error("failed to set data size: {}".format(e)) self.serial.bytesize = backup else: if self.logger: - self.logger.info("%s data size: %s" % ('set' if datasize else 'get', self.serial.bytesize)) + self.logger.info("{} data size: {}".format('set' if datasize else 'get', self.serial.bytesize)) self.rfc2217SendSubnegotiation(SERVER_SET_DATASIZE, struct.pack(b"!B", self.serial.bytesize)) elif suboption[1:2] == SET_PARITY: backup = self.serial.parity @@ -1149,11 +1154,11 @@ class PortManager(object): self.serial.parity = RFC2217_REVERSE_PARITY_MAP[parity] except ValueError as e: if self.logger: - self.logger.error("failed to set parity: %s" % (e,)) + self.logger.error("failed to set parity: {}".format(e)) self.serial.parity = backup else: if self.logger: - self.logger.info("%s parity: %s" % ('set' if parity else 'get', self.serial.parity)) + self.logger.info("{} parity: {}".format('set' if parity else 'get', self.serial.parity)) self.rfc2217SendSubnegotiation( SERVER_SET_PARITY, struct.pack(b"!B", RFC2217_PARITY_MAP[self.serial.parity])) @@ -1165,11 +1170,11 @@ class PortManager(object): self.serial.stopbits = RFC2217_REVERSE_STOPBIT_MAP[stopbits] except ValueError as e: if self.logger: - self.logger.error("failed to set stop bits: %s" % (e,)) + self.logger.error("failed to set stop bits: {}".format(e)) self.serial.stopbits = backup else: if self.logger: - self.logger.info("%s stop bits: %s" % ('set' if stopbits else 'get', self.serial.stopbits)) + self.logger.info("{} stop bits: {}".format('set' if stopbits else 'get', self.serial.stopbits)) self.rfc2217SendSubnegotiation( SERVER_SET_STOPSIZE, struct.pack(b"!B", RFC2217_STOPBIT_MAP[self.serial.stopbits])) @@ -1268,11 +1273,11 @@ class PortManager(object): elif suboption[1:2] == SET_LINESTATE_MASK: self.linstate_mask = ord(suboption[2:3]) # ensure it is a number if self.logger: - self.logger.info("line state mask: 0x%02x" % (self.linstate_mask,)) + self.logger.info("line state mask: 0x{:02x}".format(self.linstate_mask)) elif suboption[1:2] == SET_MODEMSTATE_MASK: self.modemstate_mask = ord(suboption[2:3]) # ensure it is a number if self.logger: - self.logger.info("modem state mask: 0x%02x" % (self.modemstate_mask,)) + self.logger.info("modem state mask: 0x{:02x}".format(self.modemstate_mask)) elif suboption[1:2] == PURGE_DATA: if suboption[2:3] == PURGE_RECEIVE_BUFFER: self.serial.reset_input_buffer() @@ -1292,23 +1297,23 @@ class PortManager(object): self.rfc2217SendSubnegotiation(SERVER_PURGE_DATA, PURGE_BOTH_BUFFERS) else: if self.logger: - self.logger.error("undefined PURGE_DATA: %r" % list(suboption[2:])) + self.logger.error("undefined PURGE_DATA: {!r}".format(list(suboption[2:]))) else: if self.logger: - self.logger.error("undefined COM_PORT_OPTION: %r" % list(suboption[1:])) + self.logger.error("undefined COM_PORT_OPTION: {!r}".format(list(suboption[1:]))) else: if self.logger: - self.logger.warning("unknown subnegotiation: %r" % (suboption,)) + self.logger.warning("unknown subnegotiation: {!r}".format(suboption)) # simple client test if __name__ == '__main__': import sys s = Serial('rfc2217://localhost:7000', 115200) - sys.stdout.write('%s\n' % s) + sys.stdout.write('{}\n'.format(s)) sys.stdout.write("write...\n") s.write(b"hello\n") s.flush() - sys.stdout.write("read: %s\n" % s.read(5)) + sys.stdout.write("read: {}\n".format(s.read(5))) s.close() diff --git a/serial/serialwin32.py b/serial/serialwin32.py index e2fe7f3..f33bee5 100644 --- a/serial/serialwin32.py +++ b/serial/serialwin32.py @@ -64,7 +64,7 @@ class Serial(SerialBase): 0) if self._port_handle == win32.INVALID_HANDLE_VALUE: self._port_handle = None # 'cause __del__ is called anyway - raise SerialException("could not open port %r: %r" % (self.portstr, ctypes.WinError())) + raise SerialException("could not open port {!r}: {!r}".format(self.portstr, ctypes.WinError())) try: self._overlapped_read = win32.OVERLAPPED() @@ -145,7 +145,7 @@ class Serial(SerialBase): elif self._bytesize == serial.EIGHTBITS: comDCB.ByteSize = 8 else: - raise ValueError("Unsupported number of data bits: %r" % self._bytesize) + raise ValueError("Unsupported number of data bits: {!r}".format(self._bytesize)) if self._parity == serial.PARITY_NONE: comDCB.Parity = win32.NOPARITY @@ -163,7 +163,7 @@ class Serial(SerialBase): comDCB.Parity = win32.SPACEPARITY comDCB.fParity = 1 # Enable Parity Check else: - raise ValueError("Unsupported parity mode: %r" % self._parity) + raise ValueError("Unsupported parity mode: {!r}".format(self._parity)) if self._stopbits == serial.STOPBITS_ONE: comDCB.StopBits = win32.ONESTOPBIT @@ -172,7 +172,7 @@ class Serial(SerialBase): elif self._stopbits == serial.STOPBITS_TWO: comDCB.StopBits = win32.TWOSTOPBITS else: - raise ValueError("Unsupported number of stop bits: %r" % self._stopbits) + raise ValueError("Unsupported number of stop bits: {!r}".format(self._stopbits)) comDCB.fBinary = 1 # Enable Binary Transmission # Char. w/ Parity-Err are replaced with 0xff (if fErrorChar is set to TRUE) @@ -187,24 +187,24 @@ class Serial(SerialBase): # XXX verify if platform really does not have a setting for those if not self._rs485_mode.rts_level_for_tx: raise ValueError( - 'Unsupported value for RS485Settings.rts_level_for_tx: %r' % ( - self._rs485_mode.rts_level_for_tx,)) + 'Unsupported value for RS485Settings.rts_level_for_tx: {!r}'.format( + self._rs485_mode.rts_level_for_tx,)) if self._rs485_mode.rts_level_for_rx: raise ValueError( - 'Unsupported value for RS485Settings.rts_level_for_rx: %r' % ( - self._rs485_mode.rts_level_for_rx,)) + 'Unsupported value for RS485Settings.rts_level_for_rx: {!r}'.format( + self._rs485_mode.rts_level_for_rx,)) if self._rs485_mode.delay_before_tx is not None: raise ValueError( - 'Unsupported value for RS485Settings.delay_before_tx: %r' % ( - self._rs485_mode.delay_before_tx,)) + 'Unsupported value for RS485Settings.delay_before_tx: {!r}'.format( + self._rs485_mode.delay_before_tx,)) if self._rs485_mode.delay_before_rx is not None: raise ValueError( - 'Unsupported value for RS485Settings.delay_before_rx: %r' % ( - self._rs485_mode.delay_before_rx,)) + 'Unsupported value for RS485Settings.delay_before_rx: {!r}'.format( + self._rs485_mode.delay_before_rx,)) if self._rs485_mode.loopback: raise ValueError( - 'Unsupported value for RS485Settings.loopback: %r' % ( - self._rs485_mode.loopback,)) + 'Unsupported value for RS485Settings.loopback: {!r}'.format( + self._rs485_mode.loopback,)) comDCB.fRtsControl = win32.RTS_CONTROL_TOGGLE comDCB.fOutxCtsFlow = 0 @@ -222,7 +222,9 @@ class Serial(SerialBase): comDCB.XoffChar = serial.XOFF if not win32.SetCommState(self._port_handle, ctypes.byref(comDCB)): - raise SerialException("Cannot configure port, something went wrong. Original message: %r" % ctypes.WinError()) + raise SerialException( + 'Cannot configure port, something went wrong. ' + 'Original message: {!r}'.format(ctypes.WinError())) #~ def __del__(self): #~ self.close() @@ -283,7 +285,7 @@ class Serial(SerialBase): ctypes.byref(rc), ctypes.byref(self._overlapped_read)) if not read_ok and win32.GetLastError() not in (win32.ERROR_SUCCESS, win32.ERROR_IO_PENDING): - raise SerialException("ReadFile failed (%r)" % ctypes.WinError()) + raise SerialException("ReadFile failed ({!r})".format(ctypes.WinError())) win32.GetOverlappedResult( self._port_handle, ctypes.byref(self._overlapped_read), @@ -309,7 +311,7 @@ class Serial(SerialBase): n = win32.DWORD() err = win32.WriteFile(self._port_handle, data, len(data), ctypes.byref(n), self._overlapped_write) if not err and win32.GetLastError() != win32.ERROR_IO_PENDING: - raise SerialException("WriteFile failed (%r)" % ctypes.WinError()) + raise SerialException("WriteFile failed ({!r})".format(ctypes.WinError())) if self._write_timeout != 0: # if blocking (None) or w/ write timeout (>0) # Wait for the write to complete. #~ win32.WaitForSingleObject(self._overlapped_write.hEvent, win32.INFINITE) |