RF: Replace old fashioned "except E , e" with "except E as e" (Closes #1537)

0.10 specific
supplement to b875e51cd7 in master AKA 0.9
pull/1541/head
Yaroslav Halchenko 2016-09-06 08:18:34 -04:00
parent adeb6e94a5
commit 87acd7a0fc
20 changed files with 40 additions and 40 deletions

View File

@ -171,7 +171,7 @@ after = 1.conf
parser, i = self._getSharedSCPWI(resource)
if not i:
return []
except UnicodeDecodeError, e:
except UnicodeDecodeError as e:
logSys.error("Error decoding config file '%s': %s" % (resource, e))
return []

View File

@ -228,7 +228,7 @@ class ConfigReaderUnshared(SafeConfigParserWithIncludes):
if not pOptions is None and optname in pOptions:
continue
values[optname] = v
except NoSectionError, e:
except NoSectionError as e:
if shouldExist:
raise
# No "Definition" section or wrong basedir

View File

@ -381,7 +381,7 @@ class Fail2banClient(Fail2banCmdLine, Thread):
elif not cmd == "":
try:
self.__processCommand(shlex.split(cmd))
except Exception, e: # pragma: no cover
except Exception as e: # pragma: no cover
if self._conf["verbose"] > 1:
logSys.exception(e)
else:

View File

@ -245,7 +245,7 @@ class Fail2banCmdLine():
ret = self.configurator.getOptions(jail)
self.configurator.convertToProtocol()
stream = self.configurator.getConfigStream()
except Exception, e:
except Exception as e:
logSys.error("Failed during configuration: %s" % e)
ret = False
return ret, stream

View File

@ -335,7 +335,7 @@ class Fail2banRegex(object):
if ret is not None:
found = True
regex = self._ignoreregex[ret].inc()
except RegexException, e:
except RegexException as e:
output( e )
return False
return found
@ -352,7 +352,7 @@ class Fail2banRegex(object):
regex = self._failregex[match[0]]
regex.inc()
regex.appendIP(match)
except RegexException, e:
except RegexException as e:
output( e )
return False
except IndexError:
@ -514,7 +514,7 @@ class Fail2banRegex(object):
output( "Use log file : %s" % cmd_log )
output( "Use encoding : %s" % self.encoding )
test_lines = self.file_lines_gen(hdlr)
except IOError, e:
except IOError as e:
output( e )
return False
elif cmd_log == "systemd-journal": # pragma: no cover

View File

@ -200,7 +200,7 @@ class Fail2banServer(Fail2banCmdLine):
exit(-1)
logSys.debug('Starting server done')
except Exception, e:
except Exception as e:
if self._conf["verbose"] > 1:
logSys.exception(e)
else:

View File

@ -176,7 +176,7 @@ class JailReader(ConfigReader):
self.__actions.append(action)
else:
raise AttributeError("Unable to read action")
except Exception, e:
except Exception as e:
logSys.error("Error in action definition " + act)
logSys.debug("Caught exception: %s" % (e,))
return False

View File

@ -284,7 +284,7 @@ class CommandAction(ActionBase):
res &= self.executeCmd(startCmd6, self.timeout)
if not res:
raise RuntimeError("Error starting action %s/%s" % (self._jail, self._name,))
except ValueError, e:
except ValueError as e:
raise RuntimeError("Error starting action %s/%s: %r" % (self._jail, self._name, e))
def ban(self, aInfo):

View File

@ -42,7 +42,7 @@ if sys.version_info >= (3,):
try:
x = json.dumps(x, ensure_ascii=False).encode(
locale.getpreferredencoding(), 'replace')
except Exception, e: # pragma: no cover
except Exception as e: # pragma: no cover
logSys.error('json dumps failed: %s', e)
x = '{}'
return x
@ -51,7 +51,7 @@ if sys.version_info >= (3,):
try:
x = json.loads(x.decode(
locale.getpreferredencoding(), 'replace'))
except Exception, e: # pragma: no cover
except Exception as e: # pragma: no cover
logSys.error('json loads failed: %s', e)
x = {}
return x
@ -70,7 +70,7 @@ else:
try:
x = json.dumps(_normalize(x), ensure_ascii=False).decode(
locale.getpreferredencoding(), 'replace')
except Exception, e: # pragma: no cover
except Exception as e: # pragma: no cover
logSys.error('json dumps failed: %s', e)
x = '{}'
return x
@ -79,7 +79,7 @@ else:
try:
x = _normalize(json.loads(x.decode(
locale.getpreferredencoding(), 'replace')))
except Exception, e: # pragma: no cover
except Exception as e: # pragma: no cover
logSys.error('json loads failed: %s', e)
x = {}
return x
@ -176,7 +176,7 @@ class Fail2BanDb(object):
logSys.info(
"Connected to fail2ban persistent database '%s'", filename)
except sqlite3.OperationalError, e:
except sqlite3.OperationalError as e:
logSys.error(
"Error connecting to fail2ban persistent database '%s': %s",
filename, e.args[0])

View File

@ -113,7 +113,7 @@ class Filter(JailThread):
logSys.warning(
"Mutliline regex set for jail '%s' "
"but maxlines not greater than 1")
except RegexException, e:
except RegexException as e:
logSys.error(e)
raise e
@ -146,7 +146,7 @@ class Filter(JailThread):
try:
regex = Regex(value)
self.__ignoreRegex.append(regex)
except RegexException, e:
except RegexException as e:
logSys.error(e)
raise e
@ -583,7 +583,7 @@ class Filter(JailThread):
failRegex.getMatchedLines(), fail])
if not checkAllRegex:
break
except RegexException, e: # pragma: no cover - unsure if reachable
except RegexException as e: # pragma: no cover - unsure if reachable
logSys.error(e)
return failList
@ -729,15 +729,15 @@ class FileFilter(Filter):
try:
has_content = log.open()
# see http://python.org/dev/peps/pep-3151/
except IOError, e:
except IOError as e:
logSys.error("Unable to open %s" % filename)
logSys.exception(e)
return False
except OSError, e: # pragma: no cover - requires race condition to tigger this
except OSError as e: # pragma: no cover - requires race condition to tigger this
logSys.error("Error opening %s" % filename)
logSys.exception(e)
return False
except Exception, e: # pragma: no cover - Requires implemention error in FileContainer to generate
except Exception as e: # pragma: no cover - Requires implemention error in FileContainer to generate
logSys.error("Internal error in FileContainer open method - please report as a bug to https://github.com/fail2ban/fail2ban/issues")
logSys.exception(e)
return False
@ -750,7 +750,7 @@ class FileFilter(Filter):
# initial seek to start time using half-interval search algorithm:
try:
self.seekToTime(log, startTime)
except Exception, e: # pragma: no cover
except Exception as e: # pragma: no cover
logSys.error("Error during seek to start time in \"%s\"", filename)
raise
logSys.exception(e)

View File

@ -150,7 +150,7 @@ class FilterPoll(FileFilter):
logSys.debug("%s has been modified", filename)
self.__prevStats[filename] = stats
return True
except OSError, e:
except OSError as e:
logSys.error("Unable to get stat on %s because of: %s"
% (filename, e))
self.__file404Cnt[filename] += 1

View File

@ -45,7 +45,7 @@ if not hasattr(pyinotify, '__version__') \
try:
manager = pyinotify.WatchManager()
del manager
except Exception, e:
except Exception as e:
raise ImportError("Pyinotify is probably not functional on this system: %s"
% str(e))

View File

@ -70,7 +70,7 @@ class DNSUtils:
ip = IPAddr(result[4][0])
if ip.isValid:
ips.append(ip)
except socket.error, e:
except socket.error as e:
# todo: make configurable the expired time of cache entry:
logSys.warning("Unable to find a corresponding IP address for %s: %s", dns, e)
ips = list()
@ -86,7 +86,7 @@ class DNSUtils:
# retrieve name
try:
v = socket.gethostbyaddr(ip)[0]
except socket.error, e:
except socket.error as e:
logSys.debug("Unable to find a name for the IP %s: %s", ip, e)
v = None
DNSUtils.CACHE_ipToName.set(ip, v)

View File

@ -109,7 +109,7 @@ class Jail(object):
logSys.info("Initiated %r backend" % b)
self.__actions = Actions(self)
return # we are done
except ImportError, e: # pragma: no cover
except ImportError as e: # pragma: no cover
# Log debug if auto, but error if specific
logSys.log(
logging.DEBUG if backend == "auto" else logging.ERROR,

View File

@ -138,7 +138,7 @@ class Server:
pidFile = open(pidfile, 'w')
pidFile.write("%s\n" % os.getpid())
pidFile.close()
except IOError, e:
except IOError as e:
logSys.error("Unable to create PID file: %s" % e)
# Start the communication
@ -146,13 +146,13 @@ class Server:
try:
self.__asyncServer = AsyncServer(self.__transm)
self.__asyncServer.start(sock, force)
except AsyncServerException, e:
except AsyncServerException as e:
logSys.error("Could not start server: %s", e)
# Removes the PID file.
try:
logSys.debug("Remove PID file %s" % pidfile)
os.remove(pidfile)
except OSError, e:
except OSError as e:
logSys.error("Unable to remove PID file: %s" % e)
logSys.info("Exiting Fail2ban")
@ -604,7 +604,7 @@ class Server:
# the child gets a new PID, making it impossible for its PID to equal its
# PGID.
pid = os.fork()
except OSError, e:
except OSError as e:
return (False, (e.errno, e.strerror)) # ERROR (return a tuple)
if pid == 0: # The first child.
@ -625,7 +625,7 @@ class Server:
# fork guarantees that the child is no longer a session leader, thus
# preventing the daemon from ever acquiring a controlling terminal.
pid = os.fork() # Fork a second child.
except OSError, e:
except OSError as e:
return (False, (e.errno, e.strerror)) # ERROR (return a tuple)
if (pid == 0): # The second child.

View File

@ -56,7 +56,7 @@ class Transmitter:
try:
ret = self.__commandHandler(command)
ack = 0, ret
except Exception, e:
except Exception as e:
logSys.warning("Command %r has failed. Received %r"
% (command, e))
ack = 1, e

View File

@ -421,7 +421,7 @@ class FilterReaderTest(unittest.TestCase):
# from testcase01
filterReader.get('Definition', 'failregex')
filterReader.get('Definition', 'ignoreregex')
except Exception, e: # pragma: no cover - failed if reachable
except Exception as e: # pragma: no cover - failed if reachable
self.fail('unexpected options after readexplicit: %s' % (e))
@ -771,7 +771,7 @@ filter = testfilter1
def testLogPathSystemdBackend(self):
try: # pragma: systemd no cover
from ..server.filtersystemd import FilterSystemd
except Exception, e: # pragma: no cover
except Exception as e: # pragma: no cover
raise unittest.SkipTest("systemd python interface not available")
self._testLogPath(backend='systemd')
self._testLogPath(backend='systemd[journalflags=2]')

View File

@ -102,7 +102,7 @@ def testSampleRegexsFactory(name, basedir):
if jsonREMatch:
try:
faildata = json.loads(jsonREMatch.group(1))
except ValueError, e:
except ValueError as e:
raise ValueError("%s: %s:%i" %
(e, logFile.filename(), logFile.filelineno()))
line = next(logFile)

View File

@ -1111,7 +1111,7 @@ class ServerConfigReaderTests(LogCaptureTestCase):
# command to server, use cmdHandler direct instead of `transm.proceed(cmd)`:
try:
cmdHandler(cmd)
except Exception, e: # pragma: no cover
except Exception as e: # pragma: no cover
self.fail("Command %r has failed. Received %r" % (cmd, e))
# jails = server._Server__jails

View File

@ -433,13 +433,13 @@ def gatherTests(regexps=None, opts=None):
raise ImportError('Skip, fast: %s, no_gamin: %s' % (unittest.F2B.fast, unittest.F2B.no_gamin))
from ..server.filtergamin import FilterGamin
filters.append(FilterGamin)
except ImportError, e: # pragma: no cover
except ImportError as e: # pragma: no cover
logSys.warning("Skipping gamin backend testing. Got exception '%s'" % e)
try:
from ..server.filterpyinotify import FilterPyinotify
filters.append(FilterPyinotify)
except ImportError, e: # pragma: no cover
except ImportError as e: # pragma: no cover
logSys.warning("I: Skipping pyinotify backend testing. Got exception '%s'" % e)
for Filter_ in filters:
@ -448,7 +448,7 @@ def gatherTests(regexps=None, opts=None):
try: # pragma: systemd no cover
from ..server.filtersystemd import FilterSystemd
tests.addTest(unittest.makeSuite(filtertestcase.get_monitor_failures_journal_testcase(FilterSystemd)))
except ImportError, e: # pragma: no cover
except ImportError as e: # pragma: no cover
logSys.warning("I: Skipping systemd backend testing. Got exception '%s'" % e)
# Server test for logging elements which break logging used to support