Skip to content

Commit

Permalink
Fix Python warnings (sonic-net#867)
Browse files Browse the repository at this point in the history
- Fix Python warnings flagged by "LGTM" plugin.
- Also make all 'except' statements Python3-compliant
  • Loading branch information
jleveque authored Apr 8, 2020
1 parent 2cc70f3 commit 79eb63e
Show file tree
Hide file tree
Showing 22 changed files with 53 additions and 70 deletions.
2 changes: 1 addition & 1 deletion clear/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def get_routing_stack():
proc.wait()
result = stdout.rstrip('\n')

except OSError, e:
except OSError as e:
raise OSError("Cannot detect routing-stack")

return (result)
Expand Down
2 changes: 1 addition & 1 deletion config/aaa.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ def is_ipaddress(val):
return False
try:
netaddr.IPAddress(str(val))
except:
except ValueError:
return False
return True

Expand Down
12 changes: 1 addition & 11 deletions config/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ def is_ipaddress(val):
return False
try:
netaddr.IPAddress(str(val))
except:
except ValueError:
return False
return True

Expand Down Expand Up @@ -715,7 +715,6 @@ def portchannel(ctx):
config_db = ConfigDBConnector()
config_db.connect()
ctx.obj = {'db': config_db}
pass

@portchannel.command('add')
@click.argument('portchannel_name', metavar='<portchannel_name>', required=True)
Expand Down Expand Up @@ -962,7 +961,6 @@ def warm_restart(ctx, redis_unix_socket_path):
TABLE_NAME_SEPARATOR = '|'
prefix = 'WARM_RESTART_ENABLE_TABLE' + TABLE_NAME_SEPARATOR
ctx.obj = {'db': config_db, 'state_db': state_db, 'prefix': prefix}
pass

@warm_restart.command('enable')
@click.argument('module', metavar='<module>', default='system', required=False, type=click.Choice(["system", "swss", "bgp", "teamd"]))
Expand Down Expand Up @@ -1032,7 +1030,6 @@ def vlan(ctx, redis_unix_socket_path):
config_db = ConfigDBConnector(**kwargs)
config_db.connect(wait_for_init=False)
ctx.obj = {'db': config_db}
pass

@vlan.command('add')
@click.argument('vid', metavar='<vid>', required=True, type=int)
Expand Down Expand Up @@ -1183,7 +1180,6 @@ def snmpagentaddress(ctx):
config_db = ConfigDBConnector()
config_db.connect()
ctx.obj = {'db': config_db}
pass

@snmpagentaddress.command('add')
@click.argument('agentip', metavar='<SNMP AGENT LISTENING IP Address>', required=True)
Expand Down Expand Up @@ -1233,7 +1229,6 @@ def snmptrap(ctx):
config_db = ConfigDBConnector()
config_db.connect()
ctx.obj = {'db': config_db}
pass

@snmptrap.command('modify')
@click.argument('ver', metavar='<SNMP Version>', type=click.Choice(['1', '2', '3']), required=True)
Expand Down Expand Up @@ -1362,7 +1357,6 @@ def kdump():
""" Configure kdump """
if os.geteuid() != 0:
exit("Root privileges are required for this operation")
pass

@kdump.command()
def disable():
Expand Down Expand Up @@ -1779,7 +1773,6 @@ def vrf(ctx):
config_db.connect()
ctx.obj = {}
ctx.obj['config_db'] = config_db
pass

@vrf.command('add')
@click.argument('vrf_name', metavar='<vrf_name>', required=True)
Expand Down Expand Up @@ -2342,7 +2335,6 @@ def syslog_group(ctx):
config_db = ConfigDBConnector()
config_db.connect()
ctx.obj = {'db': config_db}
pass

@syslog_group.command('add')
@click.argument('syslog_ip_address', metavar='<syslog_ip_address>', required=True)
Expand Down Expand Up @@ -2395,7 +2387,6 @@ def ntp(ctx):
config_db = ConfigDBConnector()
config_db.connect()
ctx.obj = {'db': config_db}
pass

@ntp.command('add')
@click.argument('ntp_ip_address', metavar='<ntp_ip_address>', required=True)
Expand Down Expand Up @@ -2448,7 +2439,6 @@ def sflow(ctx):
config_db = ConfigDBConnector()
config_db.connect()
ctx.obj = {'db': config_db}
pass

#
# 'sflow' command ('config sflow enable')
Expand Down
2 changes: 1 addition & 1 deletion config/mlnx.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def sniffer_env_variable_set(enable, env_variable_name, env_variable_string=""):
def restart_swss():
try:
run_command(COMMAND_RESTART_SWSS)
except OSError, e:
except OSError as e:
log_error("Not able to restart swss service, %s" % str(e), SNIFFER_SYSLOG_IDENTIFIER, True)
return 1
return 0
Expand Down
6 changes: 3 additions & 3 deletions psuutil/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ def get_platform_and_hwsku():
stdout = proc.communicate()[0]
proc.wait()
hwsku = stdout.rstrip('\n')
except OSError, e:
except OSError as e:
raise OSError("Cannot detect platform")

return (platform, hwsku)
Expand All @@ -108,14 +108,14 @@ def load_platform_psuutil():
try:
module_file = "/".join([platform_path, "plugins", PLATFORM_SPECIFIC_MODULE_NAME + ".py"])
module = imp.load_source(PLATFORM_SPECIFIC_MODULE_NAME, module_file)
except IOError, e:
except IOError as e:
log_error("Failed to load platform module '%s': %s" % (PLATFORM_SPECIFIC_MODULE_NAME, str(e)), True)
return -1

try:
platform_psuutil_class = getattr(module, PLATFORM_SPECIFIC_CLASS_NAME)
platform_psuutil = platform_psuutil_class()
except AttributeError, e:
except AttributeError as e:
log_error("Failed to instantiate '%s' class: %s" % (PLATFORM_SPECIFIC_CLASS_NAME, str(e)), True)
return -2

Expand Down
9 changes: 5 additions & 4 deletions scripts/boot_part
Original file line number Diff line number Diff line change
Expand Up @@ -62,12 +62,13 @@ def get_boot_partition(blkdev):
## Parse command output and return the current boot partition index
for line in out.splitlines():
m = re.match(r'{0}(\d+) / .*'.format(blkdev), line)
if not m: continue
if not m:
continue
index = m.group(1)
return int(index)
else:
logger.error('Unexpected /proc/mounts output: %s', out)
return None

logger.error('Unexpected /proc/mounts output: %s', out)
return None

def set_boot_partition(blkdev, index):
## Mount the partition
Expand Down
12 changes: 7 additions & 5 deletions scripts/decode-syseeprom
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ try:
import glob
from sonic_device_util import get_machine_info
from sonic_device_util import get_platform_info
except ImportError, e:
except ImportError as e:
raise ImportError (str(e) + "- required module not found")

PLATFORM_ROOT = '/usr/share/sonic/device'
Expand Down Expand Up @@ -63,6 +63,8 @@ def main():
#
run(t, opts, args, support_eeprom_db)

return 0

#-------------------------------------------------------------------------------
#
# sets global variable "optcfg"
Expand Down Expand Up @@ -103,7 +105,7 @@ def run(target, opts, args, support_eeprom_db):
if not os.path.exists(CACHE_ROOT):
try:
os.makedirs(CACHE_ROOT)
except:
except OSError:
pass
if opts.init:
for file in glob.glob(os.path.join(CACHE_ROOT, '*')):
Expand All @@ -115,7 +117,7 @@ def run(target, opts, args, support_eeprom_db):
#
try:
target.set_cache_name(os.path.join(CACHE_ROOT, CACHE_FILE))
except:
except Exception:
pass

e = target.read_eeprom()
Expand All @@ -124,7 +126,7 @@ def run(target, opts, args, support_eeprom_db):

try:
target.update_cache(e)
except:
except Exception:
pass

if opts.init:
Expand All @@ -139,7 +141,7 @@ def run(target, opts, args, support_eeprom_db):
elif opts.serial:
try:
serial = target.serial_number_str(e)
except NotImplemented, e:
except NotImplementedError as e:
print e
else:
print serial or "Undefined."
Expand Down
2 changes: 1 addition & 1 deletion scripts/fdbshow
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ class FdbShow(object):
elif 'bvid' in fdb:
try:
vlan_id = port_util.get_vlan_id_from_bvid(self.db, fdb["bvid"])
except:
except Exception:
vlan_id = fdb["bvid"]
print "Failed to get Vlan id for bvid {}\n".format(fdb["bvid"])
self.bridge_mac_list.append((int(vlan_id),) + (fdb["mac"],) + (if_name,) + (fdb_type,))
Expand Down
10 changes: 0 additions & 10 deletions scripts/natconfig
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,7 @@ class NatConfig(object):

for key,values in static_nat_dict.items():
ip_protocol = "all"
global_ip = "---"
global_port = "---"
local_ip = "---"
local_port = "---"
nat_type = "dnat"
twice_nat_id = "---"
Expand Down Expand Up @@ -106,10 +104,6 @@ class NatConfig(object):
return

for key,values in static_napt_dict.items():
ip_protocol = "all"
global_ip = "---"
global_port = "---"
local_ip = "---"
local_port = "---"
nat_type = "dnat"
twice_nat_id = "---"
Expand Down Expand Up @@ -151,8 +145,6 @@ class NatConfig(object):
return

for key,values in nat_pool_dict.items():
pool_name = "---"
global_ip = "---"
global_port = "---"

if isinstance(key, unicode) is True:
Expand Down Expand Up @@ -182,8 +174,6 @@ class NatConfig(object):
return

for key,values in nat_binding_dict.items():
binding_name = "---"
pool_name = "---"
access_list = "---"
nat_type = "snat"
twice_nat_id = "---"
Expand Down
2 changes: 1 addition & 1 deletion scripts/nbrshow
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ class NbrBase(object):
elif 'bvid' in fdb:
try:
vlan_id = port_util.get_vlan_id_from_bvid(self.db, fdb["bvid"])
except:
except Exception:
vlan_id = fdb["bvid"]
print "Failed to get Vlan id for bvid {}\n".format(fdb["bvid"])
self.bridge_mac_list.append((int(vlan_id),) + (fdb["mac"],) + (if_name,))
Expand Down
1 change: 0 additions & 1 deletion scripts/neighbor_advertiser
Original file line number Diff line number Diff line change
Expand Up @@ -266,7 +266,6 @@ def get_vlan_addresses(vlan_interface):
mac_addr = keys[1]
except Exception:
log_error('failed to get %s addresses from o.s.' % vlan_interface)
pass

if not mac_addr:
mac_addr = get_vlan_interface_mac_address(vlan_interface)
Expand Down
2 changes: 1 addition & 1 deletion scripts/pcmping
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ def create_socket(interface, portchannel):
if iface == interface:
exp_socket = s
sockets.append(s)
except:
except Exception:
sys.stderr.write("Unable to create socket. Check your permissions\n")
sys.exit(1)
return sockets, exp_socket
Expand Down
2 changes: 1 addition & 1 deletion scripts/portstat
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ class Portstat(object):
if speed is None:
speed = PORT_RATE
else:
speed = int(speed)/1000
speed = int(speed)//1000
return speed

def get_port_state(self, port_name):
Expand Down
7 changes: 5 additions & 2 deletions scripts/sonic-kdump-config
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ def get_kdump_memory():
#print(lines[0][p+2:])
#print('XXX')
return lines[0][p+2:]
except:
except Exception:
pass
return "0M-2G:256M,2G-4G:320M,4G-8G:384M,8G-:448M"

Expand All @@ -194,7 +194,7 @@ def get_kdump_num_dumps():
p = lines[0].find(': ')
if p != -1:
return int(lines[0][p+2:])
except:
except Exception:
pass
return 3

Expand Down Expand Up @@ -337,6 +337,7 @@ def cmd_kdump_config_next(verbose):
## Disable kdump
#
# @param verbose If True, the function will display a few additional information
# @return True if the grub/cmdline cfg has changed, and False if it has not
def kdump_disable(verbose, kdump_enabled, memory, num_dumps, image, cmdline_file):
write_use_kdump(0)

Expand All @@ -358,6 +359,8 @@ def kdump_disable(verbose, kdump_enabled, memory, num_dumps, image, cmdline_file
if changed:
rewrite_cfg(lines, cmdline_file)

return changed

## Command: Disable kdump
#
# @param verbose If True, the function will display a few additional information
Expand Down
8 changes: 4 additions & 4 deletions sfputil/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -313,7 +313,7 @@ def get_platform_and_hwsku():
stdout = proc.communicate()[0]
proc.wait()
hwsku = stdout.rstrip('\n')
except OSError, e:
except OSError as e:
raise OSError("Cannot detect platform")

return (platform, hwsku)
Expand Down Expand Up @@ -351,14 +351,14 @@ def load_platform_sfputil():
try:
module_file = "/".join([platform_path, "plugins", PLATFORM_SPECIFIC_MODULE_NAME + ".py"])
module = imp.load_source(PLATFORM_SPECIFIC_MODULE_NAME, module_file)
except IOError, e:
except IOError as e:
log_error("Failed to load platform module '%s': %s" % (PLATFORM_SPECIFIC_MODULE_NAME, str(e)), True)
return -1

try:
platform_sfputil_class = getattr(module, PLATFORM_SPECIFIC_CLASS_NAME)
platform_sfputil = platform_sfputil_class()
except AttributeError, e:
except AttributeError as e:
log_error("Failed to instantiate '%s' class: %s" % (PLATFORM_SPECIFIC_CLASS_NAME, str(e)), True)
return -2

Expand Down Expand Up @@ -386,7 +386,7 @@ def cli():
try:
port_config_file_path = get_path_to_port_config_file()
platform_sfputil.read_porttab_mappings(port_config_file_path)
except Exception, e:
except Exception as e:
log_error("Error reading port info (%s)" % str(e), True)
sys.exit(3)

Expand Down
6 changes: 3 additions & 3 deletions show/bgp_frr_v6.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import click
from show.main import *
from show.main import ipv6, run_command, get_bgp_summary_extended


###############################################################################
Expand All @@ -9,7 +9,7 @@
###############################################################################


@ipv6.group(cls=AliasedGroup, default_if_no_args=False)
@ipv6.group()
def bgp():
"""Show IPv6 BGP (Border Gateway Protocol) information"""
pass
Expand All @@ -22,7 +22,7 @@ def summary():
try:
device_output = run_command('sudo vtysh -c "show bgp ipv6 summary"', return_cmd=True)
get_bgp_summary_extended(device_output)
except:
except Exception:
run_command('sudo vtysh -c "show bgp ipv6 summary"')


Expand Down
Loading

0 comments on commit 79eb63e

Please sign in to comment.