From 2b5603ecf98c1c47e94a405bd98054d1703af9e7 Mon Sep 17 00:00:00 2001 From: Ilya Etingof Date: Sat, 9 Feb 2019 17:47:15 +0100 Subject: Drop Python < 2.6 except statement compatibility trick --- pysnmp/carrier/asyncio/dispatch.py | 2 +- pysnmp/carrier/asyncore/base.py | 8 +++--- pysnmp/carrier/asyncore/dgram/base.py | 38 ++++++++++++------------ pysnmp/carrier/twisted/dgram/base.py | 8 +++--- pysnmp/carrier/twisted/dgram/udp.py | 8 +++--- pysnmp/carrier/twisted/dgram/unix.py | 8 +++--- pysnmp/entity/engine.py | 4 +-- pysnmp/entity/rfc3413/cmdgen.py | 12 ++++---- pysnmp/entity/rfc3413/cmdrsp.py | 8 +++--- pysnmp/entity/rfc3413/ntforg.py | 8 +++--- pysnmp/entity/rfc3413/ntfrcv.py | 4 +-- pysnmp/hlapi/v1arch/asyncore/transport.py | 8 +++--- pysnmp/hlapi/v3arch/asyncio/transport.py | 8 +++--- pysnmp/hlapi/v3arch/asyncore/transport.py | 8 +++--- pysnmp/hlapi/v3arch/twisted/transport.py | 4 +-- pysnmp/proto/mpmod/rfc2576.py | 4 +-- pysnmp/proto/mpmod/rfc3412.py | 7 +++-- pysnmp/proto/rfc3412.py | 12 ++++---- pysnmp/proto/secmod/rfc2576.py | 8 +++--- pysnmp/proto/secmod/rfc3414/service.py | 32 ++++++++++----------- pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py | 8 +++--- pysnmp/smi/builder.py | 43 +++++++++++++--------------- pysnmp/smi/compiler.py | 4 +-- pysnmp/smi/mibs/SNMPv2-SMI.py | 41 ++++++++++---------------- pysnmp/smi/mibs/SNMPv2-TC.py | 24 ++++++++-------- pysnmp/smi/rfc1902.py | 8 +++--- 26 files changed, 158 insertions(+), 169 deletions(-) (limited to 'pysnmp') diff --git a/pysnmp/carrier/asyncio/dispatch.py b/pysnmp/carrier/asyncio/dispatch.py index e92fe95e..da1399b4 100644 --- a/pysnmp/carrier/asyncio/dispatch.py +++ b/pysnmp/carrier/asyncio/dispatch.py @@ -68,7 +68,7 @@ class AsyncioDispatcher(AbstractTransportDispatcher): raise except Exception: raise PySnmpError(';'.join(traceback.format_exception(*sys.exc_info()))) - + def registerTransport(self, tDomain, transport): if self.loopingcall is None and self.getTimerResolution() > 0: # Avoid deprecation warning for asyncio.async() diff --git a/pysnmp/carrier/asyncore/base.py b/pysnmp/carrier/asyncore/base.py index 61c55221..e4824f32 100644 --- a/pysnmp/carrier/asyncore/base.py +++ b/pysnmp/carrier/asyncore/base.py @@ -34,8 +34,8 @@ class AbstractSocketTransport(asyncore.dispatcher, AbstractTransport): ) try: sock = socket.socket(self.sockFamily, self.sockType) - except socket.error: - raise error.CarrierError('socket() failed: %s' % sys.exc_info()[1]) + except socket.error as exc: + raise error.CarrierError('socket() failed: %s' % exc) try: for b in socket.SO_RCVBUF, socket.SO_SNDBUF: @@ -43,8 +43,8 @@ class AbstractSocketTransport(asyncore.dispatcher, AbstractTransport): if bsize < self.bufferSize: sock.setsockopt(socket.SOL_SOCKET, b, self.bufferSize) debug.logger & debug.flagIO and debug.logger('%s: socket %d buffer size increased from %d to %d for buffer %d' % (self.__class__.__name__, sock.fileno(), bsize, self.bufferSize, b)) - except Exception: - debug.logger & debug.flagIO and debug.logger('%s: socket buffer size option mangling failure for buffer: %s' % (self.__class__.__name__, sys.exc_info()[1])) + except Exception as exc: + debug.logger & debug.flagIO and debug.logger('%s: socket buffer size option mangling failure for buffer: %s' % (self.__class__.__name__, exc)) # The socket map is managed by the AsyncoreDispatcher on # which this transport is registered. Here we just prepare diff --git a/pysnmp/carrier/asyncore/dgram/base.py b/pysnmp/carrier/asyncore/dgram/base.py index 95b24222..e9ffc9b0 100644 --- a/pysnmp/carrier/asyncore/dgram/base.py +++ b/pysnmp/carrier/asyncore/dgram/base.py @@ -45,16 +45,16 @@ class DgramSocketTransport(AbstractSocketTransport): if iface is not None: try: self.socket.bind(iface) - except socket.error: + except socket.error as exc: raise error.CarrierError( - 'bind() for %s failed: %s' % (iface is None and "" or iface, sys.exc_info()[1])) + 'bind() for %s failed: %s' % (iface is None and "" or iface, exc)) return self def openServerMode(self, iface): try: self.socket.bind(iface) - except socket.error: - raise error.CarrierError('bind() for %s failed: %s' % (iface, sys.exc_info()[1],)) + except socket.error as exc: + raise error.CarrierError('bind() for %s failed: %s' % (iface, exc)) return self def enableBroadcast(self, flag=1): @@ -62,8 +62,8 @@ class DgramSocketTransport(AbstractSocketTransport): self.socket.setsockopt( socket.SOL_SOCKET, socket.SO_BROADCAST, flag ) - except socket.error: - raise error.CarrierError('setsockopt() for SO_BROADCAST failed: %s' % (sys.exc_info()[1],)) + except socket.error as exc: + raise error.CarrierError('setsockopt() for SO_BROADCAST failed: %s' % exc) debug.logger & debug.flagIO and debug.logger('enableBroadcast: %s option SO_BROADCAST on socket %s' % (flag and "enabled" or "disabled", self.socket.fileno())) return self @@ -79,8 +79,8 @@ class DgramSocketTransport(AbstractSocketTransport): if self.socket.family == socket.AF_INET6: self.socket.setsockopt(socket.SOL_IPV6, socket.IPV6_RECVPKTINFO, flag) - except socket.error: - raise error.CarrierError('setsockopt() for %s failed: %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", sys.exc_info()[1])) + except socket.error as exc: + raise error.CarrierError('setsockopt() for %s failed: %s' % (self.socket.family == socket.AF_INET6 and "IPV6_RECVPKTINFO" or "IP_PKTINFO", exc)) self._sendto = sockmsg.getSendTo(self.addressType) self._recvfrom = sockmsg.getRecvFrom(self.addressType) @@ -99,8 +99,8 @@ class DgramSocketTransport(AbstractSocketTransport): socket.SOL_IPV6, socket.IPV6_TRANSPARENT, flag ) - except socket.error: - raise error.CarrierError('setsockopt() for IP_TRANSPARENT failed: %s' % sys.exc_info()[1]) + except socket.error as exc: + raise error.CarrierError('setsockopt() for IP_TRANSPARENT failed: %s' % exc) except OSError: raise error.CarrierError('IP_TRANSPARENT socket option requires superuser priveleges') @@ -148,11 +148,11 @@ class DgramSocketTransport(AbstractSocketTransport): self._sendto( self.socket, outgoingMessage, transportAddress ) - except socket.error: - if sys.exc_info()[1].args[0] in sockErrors: - debug.logger & debug.flagIO and debug.logger('handle_write: ignoring socket error %s' % (sys.exc_info()[1],)) + except socket.error as exc: + if exc.args[0] in sockErrors: + debug.logger & debug.flagIO and debug.logger('handle_write: ignoring socket error %s' % exc) else: - raise error.CarrierError('sendto() failed for %s: %s' % (transportAddress, sys.exc_info()[1])) + raise error.CarrierError('sendto() failed for %s: %s' % (transportAddress, exc)) def readable(self): return 1 @@ -169,13 +169,13 @@ class DgramSocketTransport(AbstractSocketTransport): else: self._cbFun(self, transportAddress, incomingMessage) return - except socket.error: - if sys.exc_info()[1].args[0] in sockErrors: - debug.logger & debug.flagIO and debug.logger('handle_read: known socket error %s' % (sys.exc_info()[1],)) - sockErrors[sys.exc_info()[1].args[0]] and self.handle_close() + except socket.error as exc: + if exc.args[0] in sockErrors: + debug.logger & debug.flagIO and debug.logger('handle_read: known socket error %s' % exc) + sockErrors[exc.args[0]] and self.handle_close() return else: - raise error.CarrierError('recvfrom() failed: %s' % (sys.exc_info()[1],)) + raise error.CarrierError('recvfrom() failed: %s' % exc) def handle_close(self): pass # no datagram connection diff --git a/pysnmp/carrier/twisted/dgram/base.py b/pysnmp/carrier/twisted/dgram/base.py index 4995aec4..4386b702 100644 --- a/pysnmp/carrier/twisted/dgram/base.py +++ b/pysnmp/carrier/twisted/dgram/base.py @@ -32,8 +32,8 @@ class DgramTwistedTransport(DatagramProtocol, AbstractTwistedTransport): debug.logger & debug.flagIO and debug.logger('startProtocol: transportAddress %r outgoingMessage %s' % (transportAddress, debug.hexdump(outgoingMessage))) try: self.transport.write(outgoingMessage, transportAddress) - except Exception: - raise error.CarrierError('Twisted exception: %s' % (sys.exc_info()[1],)) + except Exception as exc: + raise error.CarrierError('Twisted exception: %s' % exc) def stopProtocol(self): debug.logger & debug.flagIO and debug.logger('stopProtocol: invoked') @@ -45,5 +45,5 @@ class DgramTwistedTransport(DatagramProtocol, AbstractTwistedTransport): else: try: self.transport.write(outgoingMessage, transportAddress) - except Exception: - raise error.CarrierError('Twisted exception: %s' % (sys.exc_info()[1],)) + except Exception as exc: + raise error.CarrierError('Twisted exception: %s' % exc) diff --git a/pysnmp/carrier/twisted/dgram/udp.py b/pysnmp/carrier/twisted/dgram/udp.py index ac0f23f1..bdb93cdd 100644 --- a/pysnmp/carrier/twisted/dgram/udp.py +++ b/pysnmp/carrier/twisted/dgram/udp.py @@ -28,15 +28,15 @@ class UdpTwistedTransport(DgramTwistedTransport): iface = ('', 0) try: self._lport = reactor.listenUDP(iface[1], self, iface[0]) - except Exception: - raise error.CarrierError(sys.exc_info()[1]) + except Exception as exc: + raise error.CarrierError(exc) return self def openServerMode(self, iface): try: self._lport = reactor.listenUDP(iface[1], self, iface[0]) - except Exception: - raise error.CarrierError(sys.exc_info()[1]) + except Exception as exc: + raise error.CarrierError(exc) return self def closeTransport(self): diff --git a/pysnmp/carrier/twisted/dgram/unix.py b/pysnmp/carrier/twisted/dgram/unix.py index a256969c..fe9c459b 100644 --- a/pysnmp/carrier/twisted/dgram/unix.py +++ b/pysnmp/carrier/twisted/dgram/unix.py @@ -24,15 +24,15 @@ class UnixTwistedTransport(DgramTwistedTransport): def openClientMode(self, iface=''): try: self._lport = reactor.connectUNIXDatagram(iface, self) - except Exception: - raise error.CarrierError(sys.exc_info()[1]) + except Exception as exc: + raise error.CarrierError(exc) return self def openServerMode(self, iface): try: self._lport = reactor.listenUNIXDatagram(iface, self) - except Exception: - raise error.CarrierError(sys.exc_info()[1]) + except Exception as exc: + raise error.CarrierError(exc) return self diff --git a/pysnmp/entity/engine.py b/pysnmp/entity/engine.py index a299267c..11abec6e 100644 --- a/pysnmp/entity/engine.py +++ b/pysnmp/entity/engine.py @@ -134,9 +134,9 @@ class SnmpEngine(object): os.write(fd, str2octs(snmpEngineBoots.syntax.prettyPrint())) os.close(fd) shutil.move(fn, f) - except Exception: + except Exception as exc: debug.logger & debug.flagApp and debug.logger( - 'SnmpEngine: could not stored SNMP Engine Boots: %s' % sys.exc_info()[1]) + 'SnmpEngine: could not stored SNMP Engine Boots: %s' % exc) else: debug.logger & debug.flagApp and debug.logger( 'SnmpEngine: stored SNMP Engine Boots: %s' % snmpEngineBoots.syntax.prettyPrint()) diff --git a/pysnmp/entity/rfc3413/cmdgen.py b/pysnmp/entity/rfc3413/cmdgen.py index 98cac48c..59503d52 100644 --- a/pysnmp/entity/rfc3413/cmdgen.py +++ b/pysnmp/entity/rfc3413/cmdgen.py @@ -92,8 +92,8 @@ class CommandGenerator(object): ) return - except StatusInformation: - statusInformation = sys.exc_info()[1] + except StatusInformation as exc: + statusInformation = exc debug.logger & debug.flagApp and debug.logger( 'processResponsePdu: origSendRequestHandle %s, _sendPdu() failed with %r' % ( sendPduHandle, statusInformation)) @@ -290,8 +290,8 @@ class NextCommandGenerator(NextCommandGeneratorSingleRun): (targetName, contextEngineId, contextName, reqPDU, cbFun, cbCtx)) - except StatusInformation: - statusInformation = sys.exc_info()[1] + except StatusInformation as exc: + statusInformation = exc debug.logger & debug.flagApp and debug.logger( 'sendVarBinds: sendPduHandle %s: sendPdu() failed with %r' % (sendRequestHandle, statusInformation)) cbFun(snmpEngine, sendRequestHandle, @@ -373,8 +373,8 @@ class BulkCommandGenerator(BulkCommandGeneratorSingleRun): (targetName, nonRepeaters, maxRepetitions, contextEngineId, contextName, reqPDU, cbFun, cbCtx)) - except StatusInformation: - statusInformation = sys.exc_info()[1] + except StatusInformation as exc: + statusInformation = exc debug.logger & debug.flagApp and debug.logger( 'processResponseVarBinds: sendPduHandle %s: _sendPdu() failed with %r' % ( sendRequestHandle, statusInformation)) diff --git a/pysnmp/entity/rfc3413/cmdrsp.py b/pysnmp/entity/rfc3413/cmdrsp.py index 44d73d50..0724518a 100644 --- a/pysnmp/entity/rfc3413/cmdrsp.py +++ b/pysnmp/entity/rfc3413/cmdrsp.py @@ -116,9 +116,9 @@ class CommandResponderBase(object): statusInformation ) - except error.StatusInformation: + except error.StatusInformation as exc: debug.logger & debug.flagApp and debug.logger( - 'sendPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) + 'sendPdu: stateReference %s, statusInformation %s' % (stateReference, exc)) snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') snmpSilentDrops.syntax += 1 @@ -200,8 +200,8 @@ class CommandResponderBase(object): ) # Map ACM errors onto SMI ones - except error.StatusInformation: - statusInformation = sys.exc_info()[1] + except error.StatusInformation as exc: + statusInformation = exc debug.logger & debug.flagApp and debug.logger( '__verifyAccess: name %s, statusInformation %s' % (name, statusInformation)) errorIndication = statusInformation['errorIndication'] diff --git a/pysnmp/entity/rfc3413/ntforg.py b/pysnmp/entity/rfc3413/ntforg.py index 19442b3a..263dbb79 100644 --- a/pysnmp/entity/rfc3413/ntforg.py +++ b/pysnmp/entity/rfc3413/ntforg.py @@ -87,8 +87,8 @@ class NotificationOriginator(object): reqPDU, True, timeoutInTicks, self.processResponsePdu, (sendRequestHandle, cbFun, cbCtx) ) - except error.StatusInformation: - statusInformation = sys.exc_info()[1] + except error.StatusInformation as exc: + statusInformation = exc debug.logger & debug.flagApp and debug.logger( 'processResponsePdu: sendRequestHandle %s: sendPdu() failed with %r ' % ( sendRequestHandle, statusInformation)) @@ -303,8 +303,8 @@ class NotificationOriginator(object): (notificationHandle, cbFun, cbCtx) ) - except error.StatusInformation: - statusInformation = sys.exc_info()[1] + except error.StatusInformation as exc: + statusInformation = exc debug.logger & debug.flagApp and debug.logger( 'sendVarBinds: sendRequestHandle %s: sendPdu() failed with %r' % ( sendRequestHandle, statusInformation)) diff --git a/pysnmp/entity/rfc3413/ntfrcv.py b/pysnmp/entity/rfc3413/ntfrcv.py index fbec47ca..9e3fcc24 100644 --- a/pysnmp/entity/rfc3413/ntfrcv.py +++ b/pysnmp/entity/rfc3413/ntfrcv.py @@ -84,9 +84,9 @@ class NotificationReceiver(object): contextName, pduVersion, rspPDU, maxSizeResponseScopedPDU, stateReference, statusInformation) - except error.StatusInformation: + except error.StatusInformation as exc: debug.logger & debug.flagApp and debug.logger( - 'processPdu: stateReference %s, statusInformation %s' % (stateReference, sys.exc_info()[1])) + 'processPdu: stateReference %s, statusInformation %s' % (stateReference, exc)) snmpSilentDrops, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpSilentDrops') snmpSilentDrops.syntax += 1 diff --git a/pysnmp/hlapi/v1arch/asyncore/transport.py b/pysnmp/hlapi/v1arch/asyncore/transport.py index f0bd17e8..78630e27 100644 --- a/pysnmp/hlapi/v1arch/asyncore/transport.py +++ b/pysnmp/hlapi/v1arch/asyncore/transport.py @@ -53,9 +53,9 @@ class UdpTransportTarget(AbstractTransportTarget): socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] - except socket.gaierror: + except socket.gaierror as exc: raise error.PySnmpError('Bad IPv4/UDP transport address %s: %s' % ( - '@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) + '@'.join([str(x) for x in transportAddr]), exc)) class Udp6TransportTarget(AbstractTransportTarget): @@ -106,6 +106,6 @@ class Udp6TransportTarget(AbstractTransportTarget): socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] - except socket.gaierror: + except socket.gaierror as exc: raise error.PySnmpError('Bad IPv6/UDP transport address %s: %s' % ( - '@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) + '@'.join([str(x) for x in transportAddr]), exc)) diff --git a/pysnmp/hlapi/v3arch/asyncio/transport.py b/pysnmp/hlapi/v3arch/asyncio/transport.py index a357fa05..aeeeb51f 100644 --- a/pysnmp/hlapi/v3arch/asyncio/transport.py +++ b/pysnmp/hlapi/v3arch/asyncio/transport.py @@ -58,9 +58,9 @@ class UdpTransportTarget(AbstractTransportTarget): socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] - except socket.gaierror: + except socket.gaierror as exc: raise PySnmpError('Bad IPv4/UDP transport address %s: %s' % ( - '@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) + '@'.join([str(x) for x in transportAddr]), exc)) class Udp6TransportTarget(AbstractTransportTarget): @@ -119,6 +119,6 @@ class Udp6TransportTarget(AbstractTransportTarget): socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] - except socket.gaierror: + except socket.gaierror as exc: raise PySnmpError('Bad IPv6/UDP transport address %s: %s' % ( - '@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) + '@'.join([str(x) for x in transportAddr]), exc)) diff --git a/pysnmp/hlapi/v3arch/asyncore/transport.py b/pysnmp/hlapi/v3arch/asyncore/transport.py index 1d7bfd57..77a37c65 100644 --- a/pysnmp/hlapi/v3arch/asyncore/transport.py +++ b/pysnmp/hlapi/v3arch/asyncore/transport.py @@ -59,9 +59,9 @@ class UdpTransportTarget(AbstractTransportTarget): socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] - except socket.gaierror: + except socket.gaierror as exc: raise error.PySnmpError('Bad IPv4/UDP transport address %s: %s' % ( - '@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) + '@'.join([str(x) for x in transportAddr]), exc)) class Udp6TransportTarget(AbstractTransportTarget): @@ -117,6 +117,6 @@ class Udp6TransportTarget(AbstractTransportTarget): socket.AF_INET6, socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] - except socket.gaierror: + except socket.gaierror as exc: raise error.PySnmpError('Bad IPv6/UDP transport address %s: %s' % ( - '@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) + '@'.join([str(x) for x in transportAddr]), exc)) diff --git a/pysnmp/hlapi/v3arch/twisted/transport.py b/pysnmp/hlapi/v3arch/twisted/transport.py index 663efcf1..778060f8 100644 --- a/pysnmp/hlapi/v3arch/twisted/transport.py +++ b/pysnmp/hlapi/v3arch/twisted/transport.py @@ -56,5 +56,5 @@ class UdpTransportTarget(AbstractTransportTarget): socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)[0][4][:2] - except socket.gaierror: - raise PySnmpError('Bad IPv4/UDP transport address %s: %s' % ('@'.join([str(x) for x in transportAddr]), sys.exc_info()[1])) + except socket.gaierror as exc: + raise PySnmpError('Bad IPv4/UDP transport address %s: %s' % ('@'.join([str(x) for x in transportAddr]), exc)) diff --git a/pysnmp/proto/mpmod/rfc2576.py b/pysnmp/proto/mpmod/rfc2576.py index b355868f..9c050430 100644 --- a/pysnmp/proto/mpmod/rfc2576.py +++ b/pysnmp/proto/mpmod/rfc2576.py @@ -292,8 +292,8 @@ class SnmpV1MessageProcessingModel(AbstractMessageProcessingModel): debug.logger & debug.flagMP and debug.logger( 'prepareDataElements: SM returned securityEngineId %r securityName %r' % (securityEngineId, securityName)) - except error.StatusInformation: - statusInformation = sys.exc_info()[1] + except error.StatusInformation as exc: + statusInformation = exc snmpEngine.observer.storeExecutionContext( snmpEngine, 'rfc2576.prepareDataElements:sm-failure', diff --git a/pysnmp/proto/mpmod/rfc3412.py b/pysnmp/proto/mpmod/rfc3412.py index 58f3acc0..bda72cd9 100644 --- a/pysnmp/proto/mpmod/rfc3412.py +++ b/pysnmp/proto/mpmod/rfc3412.py @@ -530,8 +530,8 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): ) debug.logger & debug.flagMP and debug.logger('prepareDataElements: SM succeeded') - except error.StatusInformation: - statusInformation, origTraceback = sys.exc_info()[1:3] + except error.StatusInformation as exc: + statusInformation = exc debug.logger & debug.flagMP and debug.logger( 'prepareDataElements: SM failed, statusInformation %s' % statusInformation) @@ -596,8 +596,11 @@ class SnmpV3MessageProcessingModel(AbstractMessageProcessingModel): if sys.version_info[0] <= 2: raise statusInformation else: + origTraceback = sys.exc_info()[2] + try: raise statusInformation.with_traceback(origTraceback) + finally: # Break cycle between locals and traceback object # (seems to be irrelevant on Py3 but just in case) diff --git a/pysnmp/proto/rfc3412.py b/pysnmp/proto/rfc3412.py index 23f61933..11194984 100644 --- a/pysnmp/proto/rfc3412.py +++ b/pysnmp/proto/rfc3412.py @@ -330,8 +330,8 @@ class MsgAndPduDispatcher(object): debug.logger & debug.flagDsp and debug.logger('receiveMessage: MP succeded') - except error.StatusInformation: - statusInformation = sys.exc_info()[1] + except error.StatusInformation as exc: + statusInformation = exc if 'sendPduHandle' in statusInformation: # Dropped REPORT -- re-run pending reqs queue as some # of them may be waiting for this REPORT @@ -345,8 +345,8 @@ class MsgAndPduDispatcher(object): ) return restOfWholeMsg - except PyAsn1Error: - debug.logger & debug.flagMP and debug.logger('receiveMessage: %s' % (sys.exc_info()[1],)) + except PyAsn1Error as exc: + debug.logger & debug.flagMP and debug.logger('receiveMessage: %s' % exc) snmpInASNParseErrs, = snmpEngine.msgAndPduDsp.mibInstrumController.mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInASNParseErrs') snmpInASNParseErrs.syntax += 1 @@ -395,9 +395,9 @@ class MsgAndPduDispatcher(object): destTransportAddress ) - except PySnmpError: + except PySnmpError as exc: debug.logger & debug.flagDsp and debug.logger( - 'receiveMessage: report failed, statusInformation %s' % sys.exc_info()[1]) + 'receiveMessage: report failed, statusInformation %s' % exc) else: debug.logger & debug.flagDsp and debug.logger('receiveMessage: reporting succeeded') diff --git a/pysnmp/proto/secmod/rfc2576.py b/pysnmp/proto/secmod/rfc2576.py index 4cbb2f74..4b49b83a 100644 --- a/pysnmp/proto/secmod/rfc2576.py +++ b/pysnmp/proto/secmod/rfc2576.py @@ -358,9 +358,9 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel): try: return securityParameters, encoder.encode(msg) - except PyAsn1Error: + except PyAsn1Error as exc: debug.logger & debug.flagMP and debug.logger( - 'generateRequestMsg: serialization failure: %s' % sys.exc_info()[1]) + 'generateRequestMsg: serialization failure: %s' % exc) raise error.StatusInformation(errorIndication=errind.serializationError) def generateResponseMsg(self, snmpEngine, messageProcessingModel, @@ -388,9 +388,9 @@ class SnmpV1SecurityModel(base.AbstractSecurityModel): try: return communityName, encoder.encode(msg) - except PyAsn1Error: + except PyAsn1Error as exc: debug.logger & debug.flagMP and debug.logger( - 'generateResponseMsg: serialization failure: %s' % sys.exc_info()[1]) + 'generateResponseMsg: serialization failure: %s' % exc) raise error.StatusInformation(errorIndication=errind.serializationError) def processIncomingMsg(self, snmpEngine, messageProcessingModel, diff --git a/pysnmp/proto/secmod/rfc3414/service.py b/pysnmp/proto/secmod/rfc3414/service.py index a999b027..b9fa9a2c 100644 --- a/pysnmp/proto/secmod/rfc3414/service.py +++ b/pysnmp/proto/secmod/rfc3414/service.py @@ -294,9 +294,9 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): debug.logger & debug.flagSM and debug.logger('__generateRequestOrResponseMsg: clone user info') - except PyAsn1Error: + except PyAsn1Error as exc: debug.logger & debug.flagSM and debug.logger( - '__generateRequestOrResponseMsg: %s' % (sys.exc_info()[1],)) + '__generateRequestOrResponseMsg: %s' % exc) snmpInGenErrs, = mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInGenErrs') snmpInGenErrs.syntax += 1 raise error.StatusInformation( @@ -389,9 +389,9 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): try: dataToEncrypt = encoder.encode(scopedPDU) - except PyAsn1Error: + except PyAsn1Error as exc: debug.logger & debug.flagSM and debug.logger( - '__generateRequestOrResponseMsg: scopedPDU serialization error: %s' % sys.exc_info()[1]) + '__generateRequestOrResponseMsg: scopedPDU serialization error: %s' % exc) raise error.StatusInformation( errorIndication=errind.serializationError ) @@ -458,9 +458,9 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): try: msg.setComponentByPosition(2, encoder.encode(securityParameters), verifyConstraints=False) - except PyAsn1Error: + except PyAsn1Error as exc: debug.logger & debug.flagSM and debug.logger( - '__generateRequestOrResponseMsg: securityParameters serialization error: %s' % sys.exc_info()[1]) + '__generateRequestOrResponseMsg: securityParameters serialization error: %s' % exc) raise error.StatusInformation( errorIndication=errind.serializationError ) @@ -471,9 +471,9 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): try: wholeMsg = encoder.encode(msg) - except PyAsn1Error: + except PyAsn1Error as exc: debug.logger & debug.flagSM and debug.logger( - '__generateRequestOrResponseMsg: msg serialization error: %s' % sys.exc_info()[1]) + '__generateRequestOrResponseMsg: msg serialization error: %s' % exc) raise error.StatusInformation( errorIndication=errind.serializationError ) @@ -495,9 +495,9 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): try: msg.setComponentByPosition(2, encoder.encode(securityParameters), verifyConstraints=False, matchTags=False, matchConstraints=False) - except PyAsn1Error: + except PyAsn1Error as exc: debug.logger & debug.flagSM and debug.logger( - '__generateRequestOrResponseMsg: secutiryParameters serialization error: %s' % sys.exc_info()[1]) + '__generateRequestOrResponseMsg: secutiryParameters serialization error: %s' % exc) raise error.StatusInformation( errorIndication=errind.serializationError ) @@ -507,9 +507,9 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): '__generateRequestOrResponseMsg: plain outgoing msg: %s' % msg.prettyPrint()) authenticatedWholeMsg = encoder.encode(msg) - except PyAsn1Error: + except PyAsn1Error as exc: debug.logger & debug.flagSM and debug.logger( - '__generateRequestOrResponseMsg: msg serialization error: %s' % sys.exc_info()[1]) + '__generateRequestOrResponseMsg: msg serialization error: %s' % exc) raise error.StatusInformation( errorIndication=errind.serializationError ) @@ -682,8 +682,8 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): maxSizeResponseScopedPDU=maxSizeResponseScopedPDU ) - except PyAsn1Error: - debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % (sys.exc_info()[1],)) + except PyAsn1Error as exc: + debug.logger & debug.flagSM and debug.logger('processIncomingMsg: %s' % exc) snmpInGenErrs, = mibBuilder.importSymbols('__SNMPv2-MIB', 'snmpInGenErrs') snmpInGenErrs.syntax += 1 raise error.StatusInformation(errorIndication=errind.invalidMsg) @@ -948,9 +948,9 @@ class SnmpUSMSecurityModel(AbstractSecurityModel): try: scopedPDU, rest = decoder.decode(decryptedData, asn1Spec=scopedPduSpec) - except PyAsn1Error: + except PyAsn1Error as exc: debug.logger & debug.flagSM and debug.logger( - 'processIncomingMsg: scopedPDU decoder failed %s' % sys.exc_info()[0]) + 'processIncomingMsg: scopedPDU decoder failed %s' % exc) raise error.StatusInformation( errorIndication=errind.decryptionError, msgUserName=msgUserName diff --git a/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py b/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py index a043be2c..219b90d6 100644 --- a/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py +++ b/pysnmp/proto/secmod/rfc7860/auth/hmacsha2.py @@ -82,8 +82,8 @@ class HmacSha2(base.AbstractAuthenticationService): try: mac = hmac.new(authKey.asOctets(), wholeMsg, self.__hashAlgo) - except errind.ErrorIndication: - raise error.StatusInformation(errorIndication=sys.exc_info()[1]) + except errind.ErrorIndication as exc: + raise error.StatusInformation(errorIndication=exc) # 7.3.1.4 mac = mac.digest()[:self.__digestLength] @@ -111,8 +111,8 @@ class HmacSha2(base.AbstractAuthenticationService): try: mac = hmac.new(authKey.asOctets(), authenticatedWholeMsg, self.__hashAlgo) - except errind.ErrorIndication: - raise error.StatusInformation(errorIndication=sys.exc_info()[1]) + except errind.ErrorIndication as exc: + raise error.StatusInformation(errorIndication=exc) # 7.3.2.5 mac = mac.digest()[:self.__digestLength] diff --git a/pysnmp/smi/builder.py b/pysnmp/smi/builder.py index 779f39d4..01273491 100644 --- a/pysnmp/smi/builder.py +++ b/pysnmp/smi/builder.py @@ -80,15 +80,14 @@ class __AbstractMibSource(object): try: pycData, pycPath = self._getData(f + pycSfx, pycMode) - except IOError: - why = sys.exc_info()[1] - if ENOENT == -1 or why.errno == ENOENT: + except IOError as exc: + if ENOENT == -1 or exc.errno == ENOENT: debug.logger & debug.flagBld and debug.logger( - 'file %s access error: %s' % (f + pycSfx, why) + 'file %s access error: %s' % (f + pycSfx, exc) ) else: - raise error.MibLoadError('MIB file %s access error: %s' % (f + pycSfx, why)) + raise error.MibLoadError('MIB file %s access error: %s' % (f + pycSfx, exc)) else: if self.__magic == pycData[:4]: @@ -107,15 +106,14 @@ class __AbstractMibSource(object): try: pyTime = self._getTimestamp(f + pySfx) - except IOError: - why = sys.exc_info()[1] - if ENOENT == -1 or why.errno == ENOENT: + except IOError as exc: + if ENOENT == -1 or exc.errno == ENOENT: debug.logger & debug.flagBld and debug.logger( - 'file %s access error: %s' % (f + pySfx, why) + 'file %s access error: %s' % (f + pySfx, exc) ) else: - raise error.MibLoadError('MIB file %s access error: %s' % (f + pySfx, why)) + raise error.MibLoadError('MIB file %s access error: %s' % (f + pySfx, exc)) else: debug.logger & debug.flagBld and debug.logger('file %s mtime %d' % (f + pySfx, pyTime)) @@ -200,9 +198,9 @@ class ZipMibSource(__AbstractMibSource): try: return self.__loader.get_data(p), p - except Exception: # ZIP code seems to return all kinds of errors - why = sys.exc_info() - raise IOError(ENOENT, 'File or ZIP archive %s access error: %s' % (p, why[1])) + # ZIP code seems to return all kinds of errors + except Exception as exc: + raise IOError(ENOENT, 'File or ZIP archive %s access error: %s' % (p, exc)) class DirMibSource(__AbstractMibSource): @@ -213,18 +211,17 @@ class DirMibSource(__AbstractMibSource): def _listdir(self): try: return self._uniqNames(os.listdir(self._srcName)) - except OSError: - why = sys.exc_info() + except OSError as exc: debug.logger & debug.flagBld and debug.logger( - 'listdir() failed for %s: %s' % (self._srcName, why[1])) + 'listdir() failed for %s: %s' % (self._srcName, exc)) return () def _getTimestamp(self, f): p = os.path.join(self._srcName, f) try: return os.stat(p)[8] - except OSError: - raise IOError(ENOENT, 'No such file: %s' % sys.exc_info()[1], p) + except OSError as exc: + raise IOError(ENOENT, 'No such file: %s' % exc, p) def _getData(self, f, mode): p = os.path.join(self._srcName, '*') @@ -236,15 +233,15 @@ class DirMibSource(__AbstractMibSource): fp.close() return data, p - except (IOError, OSError): - why = sys.exc_info() - msg = 'File or directory %s access error: %s' % (p, why[1]) + except (IOError, OSError) as exc: + msg = 'File or directory %s access error: %s' % (p, exc) else: msg = 'No such file or directory: %s' % p raise IOError(ENOENT, msg) + class MibBuilder(object): defaultCoreMibs = os.pathsep.join( ('pysnmp.smi.mibs.instances', 'pysnmp.smi.mibs') @@ -307,9 +304,9 @@ class MibBuilder(object): try: codeObj, sfx = mibSource.read(modName) - except IOError: + except IOError as exc: debug.logger & debug.flagBld and debug.logger( - 'loadModule: read %s from %s failed: %s' % (modName, mibSource, sys.exc_info()[1])) + 'loadModule: read %s from %s failed: %s' % (modName, mibSource, exc)) continue modPath = mibSource.fullPath(modName, sfx) diff --git a/pysnmp/smi/compiler.py b/pysnmp/smi/compiler.py index b53d10e5..08e38811 100644 --- a/pysnmp/smi/compiler.py +++ b/pysnmp/smi/compiler.py @@ -28,7 +28,7 @@ try: from pysmi.codegen.pysnmp import PySnmpCodeGen, baseMibs from pysmi.compiler import MibCompiler -except ImportError: +except ImportError as exc: from pysnmp.smi import error @@ -40,7 +40,7 @@ except ImportError: return addMibCompiler - addMibCompiler = addMibCompilerDecorator(sys.exc_info()[1]) + addMibCompiler = addMibCompilerDecorator(exc) else: diff --git a/pysnmp/smi/mibs/SNMPv2-SMI.py b/pysnmp/smi/mibs/SNMPv2-SMI.py index 52e3ea11..03a085a1 100644 --- a/pysnmp/smi/mibs/SNMPv2-SMI.py +++ b/pysnmp/smi/mibs/SNMPv2-SMI.py @@ -532,9 +532,7 @@ class ManagedMibObject(ObjectType): except error.NoSuchInstanceError: val = exval.noSuchInstance - except error.SmiError: - exc = sys.exc_info()[1] - + except error.SmiError as exc: (debug.logger & debug.flagIns and debug.logger('%s: exception %r' % (self, exc))) @@ -605,9 +603,7 @@ class ManagedMibObject(ObjectType): except error.NoSuchInstanceError: val = exval.noSuchInstance - except error.SmiError: - exc = sys.exc_info()[1] - + except error.SmiError as exc: (debug.logger & debug.flagIns and debug.logger('%s: exception %r' % (self, exc))) @@ -650,9 +646,7 @@ class ManagedMibObject(ObjectType): except error.NoSuchInstanceError: val = exval.noSuchInstance - except error.SmiError: - exc = sys.exc_info()[1] - + except error.SmiError as exc: (debug.logger & debug.flagIns and debug.logger('%s: exception %r' % (self, exc))) @@ -891,8 +885,7 @@ class ManagedMibObject(ObjectType): try: node = self.getBranch(name, **context) - except (error.NoSuchInstanceError, error.NoSuchObjectError): - exc = sys.exc_info()[1] + except (error.NoSuchInstanceError, error.NoSuchObjectError) as exc: cbFun(varBind, **dict(context, error=exc)) else: @@ -958,8 +951,7 @@ class ManagedMibObject(ObjectType): try: node = self.getBranch(name, **context) - except (error.NoSuchInstanceError, error.NoSuchObjectError): - exc = sys.exc_info()[1] + except (error.NoSuchInstanceError, error.NoSuchObjectError) as exc: cbFun(varBind, **dict(context, error=exc)) else: @@ -1023,8 +1015,7 @@ class ManagedMibObject(ObjectType): try: node = self.getBranch(name, **context) - except (error.NoSuchInstanceError, error.NoSuchObjectError): - exc = sys.exc_info()[1] + except (error.NoSuchInstanceError, error.NoSuchObjectError) as exc: cbFun(varBind, **dict(context, error=exc)) else: @@ -1609,14 +1600,13 @@ class MibScalarInstance(ManagedMibObject): else: return self.syntax.clone(value) - except PyAsn1Error: - exc_t, exc_v, exc_tb = sys.exc_info() + except PyAsn1Error as exc: debug.logger & debug.flagIns and debug.logger('setValue: %s=%r failed with traceback %s' % ( - self.name, value, traceback.format_exception(exc_t, exc_v, exc_tb))) - if isinstance(exc_v, error.TableRowManagement): - raise exc_v + self.name, value, traceback.format_exception(*sys.exc_info()))) + if isinstance(exc, error.TableRowManagement): + raise exc else: - raise error.WrongValueError(name=name, idx=context.get('idx'), msg=exc_v) + raise error.WrongValueError(name=name, idx=context.get('idx'), msg=exc) # # Subtree traversal @@ -1937,16 +1927,14 @@ class MibScalarInstance(ManagedMibObject): try: instances[self.ST_CREATE][idx] = self.setValue(val, name, **context) - except error.MibOperationError: + except error.MibOperationError as exc: # SMI exceptions may carry additional content - exc = sys.exc_info()[1] if 'syntax' in exc: instances[self.ST_CREATE][idx] = exc['syntax'] cbFun(varBind, **dict(context, error=exc)) return else: - exc = sys.exc_info()[1] exc = error.WrongValueError(name=name, idx=context.get('idx'), msg=exc) cbFun(varBind, **dict(context, error=exc)) return @@ -3264,8 +3252,9 @@ class MibTableRow(ManagedMibObject): mibObj, = mibBuilder.importSymbols(modName, symName) try: syntax, instId = self.oidToValue(mibObj.syntax, instId, impliedFlag, indices) - except PyAsn1Error: - debug.logger & debug.flagIns and debug.logger('error resolving table indices at %s, %s: %s' % (self.__class__.__name__, instId, sys.exc_info()[1])) + except PyAsn1Error as exc: + debug.logger & debug.flagIns and debug.logger( + 'error resolving table indices at %s, %s: %s' % (self.__class__.__name__, instId, exc)) indices = [instId] instId = () break diff --git a/pysnmp/smi/mibs/SNMPv2-TC.py b/pysnmp/smi/mibs/SNMPv2-TC.py index 2242b91e..1367e936 100644 --- a/pysnmp/smi/mibs/SNMPv2-TC.py +++ b/pysnmp/smi/mibs/SNMPv2-TC.py @@ -62,9 +62,9 @@ class TextualConvention(object): elif displayHintType == 'd': try: return '%.*f' % (int(decimalPrecision), float(value) / pow(10, int(decimalPrecision))) - except Exception: + except Exception as exc: raise SmiError( - 'float evaluation error: %s' % sys.exc_info()[1] + 'float evaluation error: %s' % exc ) elif displayHintType == 'o': return '0%o' % value @@ -148,10 +148,10 @@ class TextualConvention(object): try: number |= octets.oct2int(numberString[0]) numberString = numberString[1:] - except Exception: + except Exception as exc: raise SmiError( 'Display format eval failure: %s: %s' - % (numberString, sys.exc_info()[1]) + % (numberString, exc) ) if displayFormat == 'x': outputValue += '%02x' % number @@ -210,23 +210,23 @@ class TextualConvention(object): return base.prettyIn(self, -int(value[3:], 16)) else: return base.prettyIn(self, int(value[2:], 16)) - except Exception: + except Exception as exc: raise SmiError( - 'integer evaluation error: %s' % sys.exc_info()[1] + 'integer evaluation error: %s' % exc ) elif displayHintType == 'd': try: return base.prettyIn(self, int(float(value) * 10**int(decimalPrecision))) - except Exception: + except Exception as exc: raise SmiError( - 'float evaluation error: %s' % sys.exc_info()[1] + 'float evaluation error: %s' % exc ) elif displayHintType == 'o' and (value.startswith('0') or value.startswith('-0')): try: return base.prettyIn(self, int(value, 8)) - except Exception: + except Exception as exc: raise SmiError( - 'octal evaluation error: %s' % sys.exc_info()[1] + 'octal evaluation error: %s' % exc ) elif displayHintType == 'b' and (value.startswith('B') or value.startswith('-B')): negative = value.startswith('-') @@ -328,10 +328,10 @@ class TextualConvention(object): try: num = int(octets.octs2str(runningValue[:guessedOctetLength]), numBase[displayFormat]) - except Exception: + except Exception as exc: raise SmiError( 'Display format eval failure: %s: %s' - % (runningValue[:guessedOctetLength], sys.exc_info()[1]) + % (runningValue[:guessedOctetLength], exc) ) num_as_bytes = [] diff --git a/pysnmp/smi/rfc1902.py b/pysnmp/smi/rfc1902.py index 83a1ec28..506434e9 100644 --- a/pysnmp/smi/rfc1902.py +++ b/pysnmp/smi/rfc1902.py @@ -505,9 +505,9 @@ class ObjectIdentity(object): instIds = rowNode.getInstIdFromIndices(*self.__args[2:]) self.__oid += instIds self.__indices = rowNode.getIndicesFromInstId(instIds) - except PyAsn1Error: + except PyAsn1Error as exc: raise SmiError('Instance index %r to OID conversion failure at object %r: %s' % ( - self.__args[2:], mibNode.getLabel(), sys.exc_info()[1])) + self.__args[2:], mibNode.getLabel(), exc)) elif self.__args[2:]: # any other kind of MIB node with indices if self.__args[2:]: instId = rfc1902.ObjectName( @@ -865,10 +865,10 @@ class ObjectType(object): try: self.__args[1] = self.__args[0].getMibNode().getSyntax().clone(self.__args[1]) - except PyAsn1Error: + except PyAsn1Error as exc: raise SmiError('MIB object %r having type %r failed to cast value %r: %s' % ( self.__args[0].prettyPrint(), self.__args[0].getMibNode().getSyntax().__class__.__name__, self.__args[1], - sys.exc_info()[1])) + exc)) if rfc1902.ObjectIdentifier().isSuperTypeOf(self.__args[1], matchConstraints=False): self.__args[1] = ObjectIdentity(self.__args[1]).resolveWithMib(mibViewController) -- cgit v1.2.1