Commit 6d2728fc authored by Michael Büsch's avatar Michael Büsch

Use context manager to suppress exceptions

Signed-off-by: Michael Büsch's avatarMichael Buesch <m@bues.ch>
parent b3de24fd
......@@ -372,10 +372,8 @@ class Project(object):
awlBase64 = p.get("CPU", srcOption)
name = None
if p.has_option("CPU", nameOption):
try:
with contextlib.suppress(ValueError):
name = base64ToStr(p.get("CPU", nameOption))
except ValueError as e:
pass
if name is None:
name = "AWL/STL #%d" % i
src = AwlSource.fromBase64(name, awlBase64)
......@@ -410,10 +408,8 @@ class Project(object):
symTabBase64 = p.get("SYMBOLS", srcOption)
name = None
if p.has_option("SYMBOLS", nameOption):
try:
with contextlib.suppress(ValueError):
name = base64ToStr(p.get("SYMBOLS", nameOption))
except ValueError as e:
pass
if name is None:
name = "Symbol table #%d" % i
src = SymTabSource.fromBase64(name, symTabBase64)
......
......@@ -65,15 +65,13 @@ class Logging(object):
@classmethod
def __print(cls, stream, text):
try:
with contextlib.suppress(RuntimeError):
if stream:
if cls.prefix:
stream.write(cls.prefix)
stream.write(text)
stream.write("\n")
stream.flush()
except RuntimeError:
pass #Ignore
@classmethod
def printDebug(cls, text):
......@@ -160,35 +158,14 @@ def awlFileWrite(filename, data, encoding="latin_1"):
if not osIsPosix:
# Can't use safe rename on non-POSIX.
# Must unlink first.
try:
with contextlib.suppress(OSError):
os.unlink(filename)
except OSError as e:
pass
os.rename(tmpFile, filename)
except (IOError, OSError, UnicodeError) as e:
raise AwlParserError("Failed to write file:\n" + str(e))
finally:
try:
with contextlib.suppress((IOError, OSError)):
os.unlink(tmpFile)
except (IOError, OSError):
pass
# Call a callable and suppress all exceptions,
# except for really fatal coding exceptions.
def CALL_NOEX(_callable, *args, **kwargs):
try:
return _callable(*args, **kwargs)
except (SyntaxError, NameError, AttributeError) as e:
raise
except ValueError as e:
import re
if re.match(r'.*takes exactly \d+ argument \(\d+ given\).*', str(e)) or\
re.match(r'.*missing \d+ required positional argument.*', str(e)) or\
re.match(r'.*takes \d+ positional argument but \d+ were given.*', str(e)):
raise
except Exception as e:
pass
return None
def strToBase64(string, ignoreErrors=False):
"""Convert a string to a base64 encoded ascii string.
......
......@@ -421,10 +421,8 @@ class AwlInsn(object): #+cdef
# Create a name2type dict for english mnemonics using the translation dict.
name2type_english = {}
for _name, _insnType in name2type_german.items():
try:
with contextlib.suppress(KeyError):
_name = german2english[_name]
except KeyError:
pass
name2type_english[_name] = _insnType
type2name_english = pivotDict(name2type_english)
......
......@@ -89,15 +89,13 @@ class Symbol(object):
if self.mnemonics != S7CPUSpecs.MNEMONICS_AUTO and\
self.mnemonics != m:
continue
try:
with contextlib.suppress(AwlSimError):
opTrans = AwlOpTranslator(insn = None,
mnemonics = m)
opDesc = opTrans.translateOp(rawInsn = None,
rawOps = newOperatorString.split())
self.setOperator(opDesc.operator)
return
except AwlSimError as e:
pass
raise AwlSimError("Symbol table parser: Can't parse symbol "
"address '%s' in line %s" %\
(newOperatorString, self.getLineNrString()))
......
......@@ -106,14 +106,12 @@ class AwlSimClient(object):
return
if self.__transceiver:
try:
with contextlib.suppress((AwlSimError, MaintenanceRequest)):
msg = AwlSimMessage_SHUTDOWN()
status = self.__sendAndWaitFor_REPLY(msg)
if status != AwlSimMessage_REPLY.STAT_OK:
printError("AwlSimClient: Failed to shut "
"down server via message")
except (AwlSimError, MaintenanceRequest) as e:
pass
self.serverProcess.terminate()
self.serverProcess.wait()
......
......@@ -1129,8 +1129,10 @@ class AwlSimMessageTransceiver(object):
def shutdown(self):
if self.sock:
CALL_NOEX(self.sock.shutdown, socket.SHUT_RDWR)
CALL_NOEX(self.sock.close)
with suppressAllExc:
self.sock.shutdown(socket.SHUT_RDWR)
with suppressAllExc:
self.sock.close()
self.sock = None
def txCork(self, cork = True):
......
......@@ -141,8 +141,10 @@ class AwlSimServer(object):
except SocketErrors as e:
result = False
if sock:
CALL_NOEX(sock.shutdown, socket.SHUT_RDWR)
CALL_NOEX(sock.close)
with suppressAllExc:
sock.shutdown(socket.SHUT_RDWR)
with suppressAllExc:
sock.close()
return result
@classmethod
......@@ -1086,13 +1088,11 @@ class AwlSimServer(object):
raise e
else:
# Send the maintenance message.
try:
with contextlib.suppress(TransferError):
if self.__clients:
# Forward it to the first client
msg = AwlSimMessage_MAINTREQ(e)
self.__clients[0].transceiver.send(msg)
except TransferError as e:
pass
except TransferError as e:
# This should be caught earlier.
printError("Uncaught transfer error: " + str(e))
......@@ -1194,14 +1194,14 @@ class AwlSimServer(object):
self.__clients = []
if self.__socket:
CALL_NOEX(self.__socket.shutdown, socket.SHUT_RDWR)
CALL_NOEX(self.__socket.close)
with suppressAllExc:
self.__socket.shutdown(socket.SHUT_RDWR)
with suppressAllExc:
self.__socket.close()
self.__socket = None
if self.__unixSockPath:
try:
with contextlib.suppress(OSError):
os.unlink(self.__unixSockPath)
except OSError as e:
pass
self.__unixSockPath = None
def shutdown(self):
......
......@@ -174,7 +174,8 @@ class GuiAwlSimClient(AwlSimClient, QObject):
if not self.setRunState(False):
raise RuntimeError
except (AwlSimError, RuntimeError) as e:
CALL_NOEX(self.killSpawnedServer)
with suppressAllExc:
self.killSpawnedServer()
self.shutdownTransceiver()
self.__setMode(self.MODE_OFFLINE)
......@@ -192,7 +193,8 @@ class GuiAwlSimClient(AwlSimClient, QObject):
port = port,
timeout = timeout)
except AwlSimError as e:
CALL_NOEX(self.shutdown)
with suppressAllExc:
self.shutdown()
raise e
self.__setMode(self.MODE_ONLINE, host = host, port = port)
......@@ -238,7 +240,8 @@ class GuiAwlSimClient(AwlSimClient, QObject):
self.shutdownTransceiver()
self.connectToServer(host = host, port = port)
except AwlSimError as e:
CALL_NOEX(self.shutdown)
with suppressAllExc:
self.shutdown()
raise e
self.__setMode(self.MODE_FORK, host = host, port = port)
self.__serverExecutable = serverExecutable
......
......@@ -447,7 +447,8 @@ class CpuWidget(QWidget):
except MaintenanceRequest as e:
self.__handleMaintenance(e)
except Exception:
CALL_NOEX(client.setRunState, False)
with suppressAllExc:
client.setRunState(False)
client.shutdown()
handleFatalException(self)
......@@ -491,7 +492,8 @@ class CpuWidget(QWidget):
except MaintenanceRequest as e:
self.__handleMaintenance(e)
except Exception:
CALL_NOEX(client.setRunState, False)
with suppressAllExc:
client.setRunState(False)
client.shutdown()
handleFatalException(self)
......@@ -570,8 +572,10 @@ class CpuWidget(QWidget):
self.__startCoreMessageHandler(fast = False)
except AwlSimError as e:
CALL_NOEX(self.__stopCoreMessageHandler)
CALL_NOEX(client.setMode_OFFLINE)
with suppressAllExc:
self.__stopCoreMessageHandler()
with suppressAllExc:
client.setMode_OFFLINE()
MessageBox.handleAwlSimError(self,
"Error while trying to connect to CPU", e)
self.goOffline()
......
......@@ -53,10 +53,8 @@ class GenericActionWidget(QWidget):
for ftype in (BlockInterfaceField.FTYPE_IN,
BlockInterfaceField.FTYPE_OUT,
BlockInterfaceField.FTYPE_INOUT):
try:
with contextlib.suppress(KeyError):
fields.extend(interfaceFields[ftype])
except KeyError:
pass
ret = [ "CALL %s%s%s" %\
(targetName,
", DB ..." if needDB else "",
......
......@@ -50,23 +50,17 @@ def __autodetectGuiFramework():
"pyqt4" : "http://www.riverbankcomputing.com/software/pyqt/download",
"pyqt5" : "http://www.riverbankcomputing.com/software/pyqt/download5",
}
try:
with contextlib.suppress(ImportError):
import PyQt5.QtCore as __pyQtCore
if __testQStringAPI(dir(__pyQtCore), True):
return "pyqt5"
except ImportError:
pass
try:
with contextlib.suppress(ImportError):
import PySide.QtCore as __pySideCore
return "pyside4"
except ImportError:
pass
try:
with contextlib.suppress(ImportError):
import PyQt4.QtCore as __pyQtCore
if __testQStringAPI(dir(__pyQtCore), True):
return "pyqt4"
except ImportError:
pass
__frameworkError("Neither PySide nor PyQt found.\n"
"PLEASE INSTALL PySide (%s)\n"
" or PyQt4 with v2 APIs (%s)\n"
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment