pylint: remove bare except

Bare except should not be used.

Reviewed-By: Petr Spacek <pspacek@redhat.com>
Reviewed-By: Lukas Slebodnik <lslebodn@redhat.com>
This commit is contained in:
Martin Basti
2016-03-11 19:51:07 +01:00
parent aa74995736
commit 491447cc5a
25 changed files with 51 additions and 57 deletions

View File

@@ -2470,11 +2470,11 @@ def install(options, env, fstore, statestore):
try: try:
socket.inet_pton(socket.AF_INET, srv) socket.inet_pton(socket.AF_INET, srv)
is_ipaddr = True is_ipaddr = True
except: except socket.error:
try: try:
socket.inet_pton(socket.AF_INET6, srv) socket.inet_pton(socket.AF_INET6, srv)
is_ipaddr = True is_ipaddr = True
except: except socket.error:
is_ipaddr = False is_ipaddr = False
if is_ipaddr: if is_ipaddr:

View File

@@ -597,7 +597,7 @@ def clean_dangling_ruvs(realm, host, options):
conn = ipaldap.IPAdmin(master_cn, 636, cacert=CACERT) conn = ipaldap.IPAdmin(master_cn, 636, cacert=CACERT)
conn.do_simple_bind(bindpw=options.dirman_passwd) conn.do_simple_bind(bindpw=options.dirman_passwd)
master_info['online'] = True master_info['online'] = True
except: except Exception:
print("The server '{host}' appears to be offline." print("The server '{host}' appears to be offline."
.format(host=master_cn)) .format(host=master_cn))
offlines.add(master_cn) offlines.add(master_cn)

View File

@@ -343,13 +343,13 @@ def ipa_stop(options):
try: try:
print("Stopping %s Service" % svc) print("Stopping %s Service" % svc)
svchandle.stop(capture_output=False) svchandle.stop(capture_output=False)
except: except Exception:
emit_err("Failed to stop %s Service" % svc) emit_err("Failed to stop %s Service" % svc)
try: try:
print("Stopping Directory Service") print("Stopping Directory Service")
dirsrv.stop(capture_output=False) dirsrv.stop(capture_output=False)
except: except Exception:
raise IpactlError("Failed to stop Directory Service") raise IpactlError("Failed to stop Directory Service")
# remove file with list of started services # remove file with list of started services
@@ -383,7 +383,7 @@ def ipa_restart(options):
emit_err("Shutting down") emit_err("Shutting down")
try: try:
dirsrv.stop(capture_output=False) dirsrv.stop(capture_output=False)
except: except Exception:
pass pass
if isinstance(e, IpactlError): if isinstance(e, IpactlError):
# do not display any other error message # do not display any other error message
@@ -421,7 +421,7 @@ def ipa_restart(options):
try: try:
print("Stopping %s Service" % svc) print("Stopping %s Service" % svc)
svchandle.stop(capture_output=False) svchandle.stop(capture_output=False)
except: except Exception:
emit_err("Failed to stop %s Service" % svc) emit_err("Failed to stop %s Service" % svc)
try: try:
@@ -521,7 +521,7 @@ def ipa_status(options):
print("%s Service: RUNNING" % svc) print("%s Service: RUNNING" % svc)
else: else:
print("%s Service: STOPPED" % svc) print("%s Service: STOPPED" % svc)
except: except Exception:
emit_err("Failed to get %s Service status" % svc) emit_err("Failed to get %s Service status" % svc)
def main(): def main():

View File

@@ -129,7 +129,7 @@ class IPADiscovery(object):
elif line.lower().startswith('search'): elif line.lower().startswith('search'):
domains += [(d, 'search domain from /etc/resolv.conf') for domains += [(d, 'search domain from /etc/resolv.conf') for
d in line.split()[1:]] d in line.split()[1:]]
except: except Exception:
pass pass
if domain: if domain:
domains = [domain] + domains domains = [domain] + domains

View File

@@ -663,7 +663,7 @@ class textui(backend.Backend):
selection = int(resp) - 1 selection = int(resp) - 1
if (selection >= 0 and selection < counter): if (selection >= 0 and selection < counter):
break break
except: except Exception:
# fall through to the error msg # fall through to the error msg
pass pass
@@ -907,7 +907,7 @@ class console(frontend.Command):
try: try:
with script: with script:
exec(script, globals(), local) exec(script, globals(), local)
except: except Exception:
traceback.print_exc() traceback.print_exc()
exit(1) exit(1)
else: else:

View File

@@ -28,10 +28,10 @@ from ipapython.version import VERSION, API_VERSION
try: try:
FQDN = socket.getfqdn() FQDN = socket.getfqdn()
except: except Exception:
try: try:
FQDN = socket.gethostname() FQDN = socket.gethostname()
except: except Exception:
FQDN = None FQDN = None
# Path to CA certificate bundle # Path to CA certificate bundle

View File

@@ -443,7 +443,7 @@ def _normalize_bind_aci(bind_acis):
netmask = "" netmask = ""
normalized.append(u"%s%s%s" % (prefix, str(ip), netmask)) normalized.append(u"%s%s%s" % (prefix, str(ip), netmask))
continue continue
except: except Exception:
normalized.append(bind_aci) normalized.append(bind_aci)
continue continue
@@ -4030,7 +4030,7 @@ class dnsrecord_del(LDAPUpdate):
try: try:
param = self.params[attr] param = self.params[attr]
attr_name = unicode(param.label or param.name) attr_name = unicode(param.label or param.name)
except: except Exception:
attr_name = attr attr_name = attr
raise errors.AttrValueNotFound(attr=attr_name, value=val) raise errors.AttrValueNotFound(attr=attr_name, value=val)
entry_attrs[attr] = list(set(old_entry[attr])) entry_attrs[attr] = list(set(old_entry[attr]))

View File

@@ -343,7 +343,7 @@ class hbactest(Command):
for rule in testrules: for rule in testrules:
try: try:
hbacset.append(self.api.Command.hbacrule_show(rule)['result']) hbacset.append(self.api.Command.hbacrule_show(rule)['result'])
except: except Exception:
pass pass
# We have some rules, import them # We have some rules, import them
@@ -426,7 +426,7 @@ class hbactest(Command):
if 'memberofindirect_group' in search_result: if 'memberofindirect_group' in search_result:
groups += search_result['memberofindirect_group'] groups += search_result['memberofindirect_group']
request.user.groups = sorted(set(groups)) request.user.groups = sorted(set(groups))
except: except Exception:
pass pass
if options['service'] != u'all': if options['service'] != u'all':
@@ -435,7 +435,7 @@ class hbactest(Command):
service_result = self.api.Command.hbacsvc_show(request.service.name)['result'] service_result = self.api.Command.hbacsvc_show(request.service.name)['result']
if 'memberof_hbacsvcgroup' in service_result: if 'memberof_hbacsvcgroup' in service_result:
request.service.groups = service_result['memberof_hbacsvcgroup'] request.service.groups = service_result['memberof_hbacsvcgroup']
except: except Exception:
pass pass
if options['targethost'] != u'all': if options['targethost'] != u'all':
@@ -446,7 +446,7 @@ class hbactest(Command):
if 'memberofindirect_hostgroup' in tgthost_result: if 'memberofindirect_hostgroup' in tgthost_result:
groups += tgthost_result['memberofindirect_hostgroup'] groups += tgthost_result['memberofindirect_hostgroup']
request.targethost.groups = sorted(set(groups)) request.targethost.groups = sorted(set(groups))
except: except Exception:
pass pass
matched_rules = [] matched_rules = []

View File

@@ -565,7 +565,7 @@ class stageuser_activate(LDAPQuery):
try: try:
v.decode('utf-8') v.decode('utf-8')
self.log.debug("merge: %s:%r wiped" % (attr, v)) self.log.debug("merge: %s:%r wiped" % (attr, v))
except: except ValueError:
self.log.debug("merge %s: [no_print %s]" % (attr, v.__class__.__name__)) self.log.debug("merge %s: [no_print %s]" % (attr, v.__class__.__name__))
if isinstance(entry_to[attr], (list, tuple)): if isinstance(entry_to[attr], (list, tuple)):
# multi value attribute # multi value attribute
@@ -581,7 +581,7 @@ class stageuser_activate(LDAPQuery):
try: try:
v.decode('utf-8') v.decode('utf-8')
self.log.debug("Add: %s:%r" % (attr, v)) self.log.debug("Add: %s:%r" % (attr, v))
except: except ValueError:
self.log.debug("Add %s: [no_print %s]" % (attr, v.__class__.__name__)) self.log.debug("Add %s: [no_print %s]" % (attr, v.__class__.__name__))
if isinstance(entry_to[attr], (list, tuple)): if isinstance(entry_to[attr], (list, tuple)):
@@ -692,7 +692,7 @@ class stageuser_activate(LDAPQuery):
try: try:
self.log.error("Fail to delete the Staging user after activating it %s " % (staging_dn)) self.log.error("Fail to delete the Staging user after activating it %s " % (staging_dn))
self._exc_wrapper(args, options, ldap.delete_entry)(active_dn) self._exc_wrapper(args, options, ldap.delete_entry)(active_dn)
except: except Exception:
self.log.error("Fail to cleanup activation. The user remains active %s" % (active_dn)) self.log.error("Fail to cleanup activation. The user remains active %s" % (active_dn))
raise raise

View File

@@ -731,7 +731,7 @@ class user_del(baseuser_del):
try: try:
self._preserve_user(pkey, delete_container, **options) self._preserve_user(pkey, delete_container, **options)
preserved.append(pkey_to_value(pkey, options)) preserved.append(pkey_to_value(pkey, options))
except: except Exception:
if not options.get('continue', False): if not options.get('continue', False):
raise raise
failed.append(pkey_to_value(pkey, options)) failed.append(pkey_to_value(pkey, options))

View File

@@ -434,7 +434,7 @@ class SystemdService(PlatformService):
os.unlink(srv_lnk) os.unlink(srv_lnk)
os.symlink(self.lib_path, srv_lnk) os.symlink(self.lib_path, srv_lnk)
ipautil.run([paths.SYSTEMCTL, "--system", "daemon-reload"]) ipautil.run([paths.SYSTEMCTL, "--system", "daemon-reload"])
except: except Exception:
pass pass
else: else:
self.__enable(instance_name) self.__enable(instance_name)
@@ -457,7 +457,7 @@ class SystemdService(PlatformService):
if os.path.islink(srv_lnk): if os.path.islink(srv_lnk):
os.unlink(srv_lnk) os.unlink(srv_lnk)
ipautil.run([paths.SYSTEMCTL, "--system", "daemon-reload"]) ipautil.run([paths.SYSTEMCTL, "--system", "daemon-reload"])
except: except Exception:
pass pass
else: else:
try: try:

View File

@@ -160,19 +160,19 @@ def __parse_config(discover_server = True):
try: try:
if not config.default_realm: if not config.default_realm:
config.default_realm = p.get("global", "realm") config.default_realm = p.get("global", "realm")
except: except AttributeError:
pass pass
if discover_server: if discover_server:
try: try:
s = p.get("global", "xmlrpc_uri") s = p.get("global", "xmlrpc_uri")
server = urlsplit(s) server = urlsplit(s)
config.default_server.append(server.netloc) config.default_server.append(server.netloc)
except: except Exception:
pass pass
try: try:
if not config.default_domain: if not config.default_domain:
config.default_domain = p.get("global", "domain") config.default_domain = p.get("global", "domain")
except: except AttributeError:
pass pass
def __discover_config(discover_server = True): def __discover_config(discover_server = True):
@@ -218,7 +218,7 @@ def __discover_config(discover_server = True):
hostname = str(server.target).rstrip(".") hostname = str(server.target).rstrip(".")
config.default_server.append(hostname) config.default_server.append(hostname)
except: except Exception:
pass pass
def add_standard_options(parser): def add_standard_options(parser):

View File

@@ -505,7 +505,7 @@ def file_exists(filename):
return True return True
else: else:
return False return False
except: except Exception:
return False return False
def dir_exists(filename): def dir_exists(filename):
@@ -515,7 +515,7 @@ def dir_exists(filename):
return True return True
else: else:
return False return False
except: except Exception:
return False return False
def install_file(fname, dest): def install_file(fname, dest):

View File

@@ -606,7 +606,7 @@ def parse_log_level(level):
if isinstance(level, six.string_types): if isinstance(level, six.string_types):
try: try:
level = int(level) level = int(level)
except: except ValueError:
pass pass
# If it's a string lookup it's name and map to logging level # If it's a string lookup it's name and map to logging level

View File

@@ -223,17 +223,12 @@ class NSSConnection(httplib.HTTPConnection, NSSAddressFamilyFallback):
self.tls_version_max = str(tls_version_max) self.tls_version_max = str(tls_version_max)
def _create_socket(self): def _create_socket(self):
# TODO: remove the try block once python-nss is guaranteed to contain ssl_enable_renegotiation = getattr(
# these values ssl, 'SSL_ENABLE_RENEGOTIATION', 20)
try: ssl_require_safe_negotiation = getattr(
#pylint: disable=E1101 ssl,'SSL_REQUIRE_SAFE_NEGOTIATION', 21)
ssl_enable_renegotiation = ssl.SSL_ENABLE_RENEGOTIATION ssl_renegotiate_requires_xtn = getattr(
ssl_require_safe_negotiation = ssl.SSL_REQUIRE_SAFE_NEGOTIATION ssl, 'SSL_RENEGOTIATE_REQUIRES_XTN', 2)
ssl_renegotiate_requires_xtn = ssl.SSL_RENEGOTIATE_REQUIRES_XTN
except:
ssl_enable_renegotiation = 20
ssl_require_safe_negotiation = 21
ssl_renegotiate_requires_xtn = 2
# Create the socket here so we can do things like let the caller # Create the socket here so we can do things like let the caller
# override the NSS callbacks # override the NSS callbacks

View File

@@ -571,7 +571,7 @@ class DnsBackup(object):
try: try:
delkw = { '%srecord' % str(type.lower()) : unicode(rdata) } delkw = { '%srecord' % str(type.lower()) : unicode(rdata) }
api.Command.dnsrecord_del(unicode(zone), unicode(host), **delkw) api.Command.dnsrecord_del(unicode(zone), unicode(host), **delkw)
except: except Exception:
pass pass
j += 1 j += 1
@@ -662,7 +662,7 @@ class BindInstance(service.Service):
try: try:
self.stop() self.stop()
except: except Exception:
pass pass
# get a connection to the DS # get a connection to the DS

View File

@@ -127,7 +127,7 @@ class CertDB(object):
shutil.rmtree(self.reqdir, ignore_errors=True) shutil.rmtree(self.reqdir, ignore_errors=True)
try: try:
os.chdir(self.cwd) os.chdir(self.cwd)
except: except OSError:
pass pass
def setup_cert_request(self): def setup_cert_request(self):

View File

@@ -122,7 +122,7 @@ class DNSKeySyncInstance(service.Service):
self.suffix = ipautil.realm_to_suffix(self.realm) self.suffix = ipautil.realm_to_suffix(self.realm)
try: try:
self.stop() self.stop()
except: except Exception:
pass pass
# get a connection to the DS # get a connection to the DS

View File

@@ -120,10 +120,10 @@ def get_fqdn():
fqdn = "" fqdn = ""
try: try:
fqdn = socket.getfqdn() fqdn = socket.getfqdn()
except: except Exception:
try: try:
fqdn = socket.gethostname() fqdn = socket.gethostname()
except: except Exception:
fqdn = "" fqdn = ""
return fqdn return fqdn

View File

@@ -135,7 +135,7 @@ class KrbInstance(service.Service):
self.backup_state("running", self.is_running()) self.backup_state("running", self.is_running())
try: try:
self.stop() self.stop()
except: except Exception:
# It could have been not running # It could have been not running
pass pass
@@ -210,7 +210,7 @@ class KrbInstance(service.Service):
def __start_instance(self): def __start_instance(self):
try: try:
self.start() self.start()
except: except Exception:
root_logger.critical("krb5kdc service failed to start") root_logger.critical("krb5kdc service failed to start")
def __setup_sub_dict(self): def __setup_sub_dict(self):
@@ -386,7 +386,7 @@ class KrbInstance(service.Service):
try: try:
self.stop() self.stop()
except: except Exception:
pass pass
for f in [paths.KRB5KDC_KDC_CONF, paths.KRB5_CONF]: for f in [paths.KRB5KDC_KDC_CONF, paths.KRB5_CONF]:

View File

@@ -50,7 +50,7 @@ class ODSExporterInstance(service.Service):
try: try:
self.stop() self.stop()
except: except Exception:
pass pass
# get a connection to the DS # get a connection to the DS

View File

@@ -286,7 +286,7 @@ def common_cleanup(func):
# what is the state of the environment # what is the state of the environment
try: try:
installer._fstore.restore_file(paths.HOSTS) installer._fstore.restore_file(paths.HOSTS)
except: except Exception:
pass pass
return decorated return decorated

View File

@@ -1978,7 +1978,7 @@ class RestClient(Backend):
def _parse_dogtag_error(body): def _parse_dogtag_error(body):
try: try:
return pki.PKIException.from_json(json.loads(body)) return pki.PKIException.from_json(json.loads(body))
except: except Exception:
return None return None
def __init__(self, api): def __init__(self, api):

View File

@@ -38,7 +38,7 @@ def make_ipaddress_checker(addr, words=None, prefixlen=None):
try: try:
ip = ipautil.CheckedIPAddress(addr, match_local=False) ip = ipautil.CheckedIPAddress(addr, match_local=False)
assert ip.words == words and ip.prefixlen == prefixlen assert ip.words == words and ip.prefixlen == prefixlen
except: except Exception:
assert words is None and prefixlen is None assert words is None and prefixlen is None
check_ipaddress.description = "Test IP address parsing and verification (%s)" % addr check_ipaddress.description = "Test IP address parsing and verification (%s)" % addr
return check_ipaddress return check_ipaddress

View File

@@ -26,7 +26,6 @@ disable=
attribute-defined-outside-init, attribute-defined-outside-init,
bad-builtin, bad-builtin,
bad-indentation, bad-indentation,
bare-except,
broad-except, broad-except,
dangerous-default-value, dangerous-default-value,
eval-used, eval-used,