From 3d093ecb304485f139c841ffd9d418d8f589ff1a Mon Sep 17 00:00:00 2001 From: Joe LeVeque Date: Tue, 11 Aug 2020 00:35:38 +0000 Subject: [PATCH 1/7] Python 3 compliance --- config/aaa.py | 8 ++--- config/main.py | 2 +- config/mlnx.py | 14 ++++----- consutil/main.py | 2 +- counterpoll/main.py | 2 +- crm/main.py | 32 ++++++++++---------- pcieutil/main.py | 10 +++---- pddf_thermalutil/main.py | 28 +++++++++--------- pfc/main.py | 20 ++++++------- pfcwd/main.py | 4 +-- scripts/boot_part | 4 +-- scripts/decode-syseeprom | 18 ++++++------ scripts/fast-reboot-dump.py | 4 +-- scripts/fdbclear | 2 +- scripts/fdbshow | 8 ++--- scripts/gearboxutil | 10 +++---- scripts/intfstat | 34 +++++++++++----------- scripts/intfutil | 8 ++--- scripts/natclear | 8 ++--- scripts/natconfig | 58 ++++++++++++++++++------------------- scripts/natshow | 38 ++++++++++++------------ scripts/nbrshow | 10 +++---- scripts/pcmping | 18 ++++++------ scripts/pfcstat | 27 ++++++++--------- scripts/portstat | 26 ++++++++--------- scripts/psushow | 10 +++---- scripts/queuestat | 38 ++++++++++++------------ scripts/sfpshow | 2 +- scripts/sonic-kdump-config | 4 +-- scripts/teamshow | 4 +-- scripts/watermarkcfg | 4 +-- scripts/watermarkstat | 24 +++++++-------- sfputil/main.py | 50 ++++++++++++++++---------------- show/main.py | 14 ++++----- show/mlnx.py | 10 +++---- ssdutil/main.py | 14 ++++----- tests/config_test.py | 10 +++---- utilities_common/cli.py | 2 +- 38 files changed, 290 insertions(+), 291 deletions(-) diff --git a/config/aaa.py b/config/aaa.py index 8cdd818ac0..fdb85c3f27 100644 --- a/config/aaa.py +++ b/config/aaa.py @@ -70,7 +70,7 @@ def fallback(option): def login(auth_protocol): """Switch login authentication [ {tacacs+, local} | default ]""" if len(auth_protocol) is 0: - print 'Not support empty argument' + click.echo('Argument "auth_protocol" is required') return if 'default' in auth_protocol: @@ -107,7 +107,7 @@ def timeout(ctx, second): elif second: add_table_kv('TACPLUS', 'global', 'timeout', second) else: - click.echo('Not support empty argument') + click.echo('Argument "second" is required') tacacs.add_command(timeout) default.add_command(timeout) @@ -122,7 +122,7 @@ def authtype(ctx, type): elif type: add_table_kv('TACPLUS', 'global', 'auth_type', type) else: - click.echo('Not support empty argument') + click.echo('Argument "type" is required') tacacs.add_command(authtype) default.add_command(authtype) @@ -137,7 +137,7 @@ def passkey(ctx, secret): elif secret: add_table_kv('TACPLUS', 'global', 'passkey', secret) else: - click.echo('Not support empty argument') + click.echo('Argument "secret" is required') tacacs.add_command(passkey) default.add_command(passkey) diff --git a/config/main.py b/config/main.py index fc451f37b7..6822077099 100755 --- a/config/main.py +++ b/config/main.py @@ -818,7 +818,7 @@ def config(ctx): try: version_info = device_info.get_sonic_version_info() asic_type = version_info['asic_type'] - except KeyError, TypeError: + except (KeyError, TypeError): raise click.Abort() if asic_type == 'mellanox': diff --git a/config/mlnx.py b/config/mlnx.py index bd8c8c9425..8c97d3b382 100644 --- a/config/mlnx.py +++ b/config/mlnx.py @@ -100,7 +100,7 @@ def sniffer_env_variable_set(enable, env_variable_name, env_variable_string=""): env_variable_exist_string = env_variable_read(env_variable_name) if env_variable_exist_string: if enable is True: - print "sniffer is already enabled, do nothing" + click.echo("sniffer is already enabled, do nothing") ignore = True else: env_variable_delete(env_variable_exist_string) @@ -108,7 +108,7 @@ def sniffer_env_variable_set(enable, env_variable_name, env_variable_string=""): if enable is True: env_variable_write(env_variable_string) else: - print "sniffer is already disabled, do nothing" + click.echo("sniffer is already disabled, do nothing") ignore = True if not ignore: @@ -164,9 +164,9 @@ def sdk(): prompt='Swss service will be restarted, continue?') def enable(): """Enable SDK Sniffer""" - print "Enabling SDK sniffer" + click.echo("Enabling SDK sniffer") sdk_sniffer_enable() - print "Note: the sniffer file may exhaust the space on /var/log, please disable it when you are done with this sniffering." + click.echo("Note: the sniffer file may exhaust the space on /var/log, please disable it when you are done with this sniffering.") @sdk.command() @@ -174,7 +174,7 @@ def enable(): prompt='Swss service will be restarted, continue?') def disable(): """Disable SDK Sniffer""" - print "Disabling SDK sniffer" + click.echo("Disabling SDK sniffer") sdk_sniffer_disable() @@ -198,7 +198,7 @@ def sdk_sniffer_enable(): err = restart_swss() if err is not 0: return - print 'SDK sniffer is Enabled, recording file is %s.' % sdk_sniffer_filename + click.echo('SDK sniffer is Enabled, recording file is %s.' % sdk_sniffer_filename) else: pass @@ -211,7 +211,7 @@ def sdk_sniffer_disable(): err = restart_swss() if err is not 0: return - print "SDK sniffer is Disabled." + click.echo("SDK sniffer is Disabled.") else: pass diff --git a/consutil/main.py b/consutil/main.py index c9a914d478..faddeb33e9 100644 --- a/consutil/main.py +++ b/consutil/main.py @@ -20,7 +20,7 @@ def consutil(): """consutil - Command-line utility for interacting with switches via console device""" if os.geteuid() != 0: - print "Root privileges are required for this operation" + click.echo("Root privileges are required for this operation") sys.exit(1) # 'show' subcommand diff --git a/counterpoll/main.py b/counterpoll/main.py index 55f1aefeba..1f56fadaa2 100644 --- a/counterpoll/main.py +++ b/counterpoll/main.py @@ -186,5 +186,5 @@ def show(): if buffer_pool_wm_info: data.append(["BUFFER_POOL_WATERMARK_STAT", buffer_pool_wm_info.get("POLL_INTERVAL", DEFLT_10_SEC), buffer_pool_wm_info.get("FLEX_COUNTER_STATUS", DISABLE)]) - print tabulate(data, headers=header, tablefmt="simple", missingval="") + click.echo(tabulate(data, headers=header, tablefmt="simple", missingval="")) diff --git a/crm/main.py b/crm/main.py index 241874e6e8..4388521def 100644 --- a/crm/main.py +++ b/crm/main.py @@ -29,9 +29,9 @@ def show_summary(self): crm_info = configdb.get_entry('CRM', 'Config') if crm_info: - print '\nPolling Interval: ' + crm_info['polling_interval'] + ' second(s)\n' + click.echo('\nPolling Interval: ' + crm_info['polling_interval'] + ' second(s)\n') else: - print '\nError! Could not get CRM configuration.\n' + click.echo('\nError! Could not get CRM configuration.\n') def show_thresholds(self, resource): """ @@ -54,11 +54,11 @@ def show_thresholds(self, resource): else: data.append([resource, crm_info[resource + "_threshold_type"], crm_info[resource + "_low_threshold"], crm_info[resource + "_high_threshold"]]) else: - print '\nError! Could not get CRM configuration.' + click.echo('\nError! Could not get CRM configuration.') - print '\n' - print tabulate(data, headers=header, tablefmt="simple", missingval="") - print '\n' + click.echo('\n') + click.echo(tabulate(data, headers=header, tablefmt="simple", missingval="")) + click.echo('\n') def show_resources(self, resource): """ @@ -80,11 +80,11 @@ def show_resources(self, resource): else: data.append([resource, crm_stats['crm_stats_' + resource + "_used"], crm_stats['crm_stats_' + resource + "_available"]]) else: - print '\nCRM counters are not ready. They would be populated after the polling interval.' + click.echo('\nCRM counters are not ready. They would be populated after the polling interval.') - print '\n' - print tabulate(data, headers=header, tablefmt="simple", missingval="") - print '\n' + click.echo('\n') + click.echo(tabulate(data, headers=header, tablefmt="simple", missingval="")) + click.echo('\n') def show_acl_resources(self): """ @@ -108,9 +108,9 @@ def show_acl_resources(self): crm_stats['crm_stats_' + res + "_available"] ]) - print '\n' - print tabulate(data, headers=header, tablefmt="simple", missingval="") - print '\n' + click.echo('\n') + click.echo(tabulate(data, headers=header, tablefmt="simple", missingval="")) + click.echo('\n') def show_acl_table_resources(self): """ @@ -136,9 +136,9 @@ def show_acl_table_resources(self): if ('crm_stats_' + res + '_used' in crm_stats) and ('crm_stats_' + res + '_available' in crm_stats): data.append([id, res, crm_stats['crm_stats_' + res + '_used'], crm_stats['crm_stats_' + res + '_available']]) - print '\n' - print tabulate(data, headers=header, tablefmt="simple", missingval="") - print '\n' + click.echo('\n') + click.echo(tabulate(data, headers=header, tablefmt="simple", missingval="")) + click.echo('\n') @click.group() diff --git a/pcieutil/main.py b/pcieutil/main.py index 5eedd678f1..ca1dd0fb96 100644 --- a/pcieutil/main.py +++ b/pcieutil/main.py @@ -33,7 +33,7 @@ def print_result(name, result): sys.stdout.write(string) for i in xrange(int(length)): sys.stdout.write("-") - print(' [%s]' % result) + click.echo(' [%s]' % result) # ==================== Methods for initialization ==================== @@ -103,7 +103,7 @@ def pcie_show(): Fn = item["fn"] Name = item["name"] Id = item["id"] - print "bus:dev.fn %s:%s.%s - dev_id=0x%s, %s" % (Bus, Dev, Fn, Id, Name) + click.echo("bus:dev.fn %s:%s.%s - dev_id=0x%s, %s" % (Bus, Dev, Fn, Id, Name)) # Show PCIE Vender ID and Device ID @@ -122,9 +122,9 @@ def pcie_check(): log.log_warning("PCIe Device: " + item["name"] + " Not Found") err += 1 if err: - print "PCIe Device Checking All Test ----------->>> FAILED" + click.echo("PCIe Device Checking All Test ----------->>> FAILED") else: - print "PCIe Device Checking All Test ----------->>> PASSED" + click.echo("PCIe Device Checking All Test ----------->>> PASSED") @cli.command() @@ -132,7 +132,7 @@ def pcie_check(): def pcie_generate(): '''Generate config file with current pci device''' platform_pcieutil.dump_conf_yaml() - print "Generate config file pcie.yaml under path %s" % platform_plugins_path + click.echo("Generate config file pcie.yaml under path %s" % platform_plugins_path) if __name__ == '__main__': diff --git a/pddf_thermalutil/main.py b/pddf_thermalutil/main.py index 1be6381eec..ee32769635 100644 --- a/pddf_thermalutil/main.py +++ b/pddf_thermalutil/main.py @@ -135,19 +135,19 @@ def gettemp(index): except NotImplementedError: pass - else: - label, value = platform_thermalutil.show_thermal_temp_values(thermal) + else: + label, value = platform_thermalutil.show_thermal_temp_values(thermal) - if label is None: - status_table.append([thermal_name, value]) - else: - status_table.append([thermal_name, label, value]) + if label is None: + status_table.append([thermal_name, value]) + else: + status_table.append([thermal_name, label, value]) if status_table: - if label is None: - header = ['Temp Sensor', 'Value'] - else: - header = ['Temp Sensor', 'Label', 'Value'] + if label is None: + header = ['Temp Sensor', 'Value'] + else: + header = ['Temp Sensor', 'Label', 'Value'] click.echo(tabulate(status_table, header, tablefmt="simple")) @cli.group() @@ -159,11 +159,11 @@ def debug(): def dump_sysfs(): """Dump all Temp Sensor related SysFS paths""" if platform_chassis is not None: - supported_thermal = range(1, _wrapper_get_num_thermals()+ 1) - for index in supported_thermal: - status = platform_chassis.get_thermal(index-1).dump_sysfs() + supported_thermal = range(1, _wrapper_get_num_thermals()+ 1) + for index in supported_thermal: + status = platform_chassis.get_thermal(index-1).dump_sysfs() else: - status = platform_thermalutil.dump_sysfs() + status = platform_thermalutil.dump_sysfs() if status: for i in status: diff --git a/pfc/main.py b/pfc/main.py index 9da2147070..9a5c4b5e8f 100644 --- a/pfc/main.py +++ b/pfc/main.py @@ -45,16 +45,16 @@ def showPfcAsym(interface): sorted_table = natsorted(table) - print '\n' - print tabulate(sorted_table, headers=header, tablefmt="simple", missingval="") - print '\n' + click.echo('\n') + click.echo(tabulate(sorted_table, headers=header, tablefmt="simple", missingval="")) + click.echo('\n') def configPfcPrio(status, interface, priority): configdb = swsssdk.ConfigDBConnector() configdb.connect() if interface not in configdb.get_keys('PORT_QOS_MAP'): - print 'Cannot find interface {0}'.format(interface) + click.echo('Cannot find interface {0}'.format(interface)) return """Current lossless priorities on the interface""" @@ -65,11 +65,11 @@ def configPfcPrio(status, interface, priority): enable_prio = [x.strip() for x in enable_prio if x.strip()] if status == 'on' and priority in enable_prio: - print 'Priority {0} has already been enabled on {1}'.format(priority, interface) + click.echo('Priority {0} has already been enabled on {1}'.format(priority, interface)) return if status == 'off' and priority not in enable_prio: - print 'Priority {0} is not enabled on {1}'.format(priority, interface) + click.echo('Priority {0} is not enabled on {1}'.format(priority, interface)) return if status == 'on': @@ -99,7 +99,7 @@ def showPfcPrio(interface): """The user specifies an interface but we cannot find it""" if interface and interface not in intfs: - print 'Cannot find interface {0}'.format(interface) + click.echo('Cannot find interface {0}'.format(interface)) return if interface: @@ -110,9 +110,9 @@ def showPfcPrio(interface): table.append([intf, entry.get('pfc_enable', 'N/A')]) sorted_table = natsorted(table) - print '\n' - print tabulate(sorted_table, headers=header, tablefmt="simple", missingval="") - print '\n' + click.echo('\n') + click.echo(tabulate(sorted_table, headers=header, tablefmt="simple", missingval="")) + click.echo('\n') @click.group() def cli(): diff --git a/pfcwd/main.py b/pfcwd/main.py index fbb944009c..8d87053e2a 100644 --- a/pfcwd/main.py +++ b/pfcwd/main.py @@ -171,7 +171,7 @@ def start(action, restoration_time, ports, detection_time): pfcwd_info['restoration_time'] = restoration_time else: pfcwd_info['restoration_time'] = 2 * detection_time - print "restoration time not defined; default to 2 times detection time: %d ms" % (2 * detection_time) + click.echo("restoration time not defined; default to 2 times detection time: %d ms" % (2 * detection_time)) for port in ports: if port == "all": @@ -209,7 +209,7 @@ def interval(poll_interval): entry_min = restoration_time_entry_value entry_min_str = "restoration time" if entry_min < poll_interval: - print >> sys.stderr, "unable to use polling interval = {}ms, value is bigger than one of the configured {} values, please choose a smaller polling_interval".format(poll_interval,entry_min_str) + click.echo("unable to use polling interval = {}ms, value is bigger than one of the configured {} values, please choose a smaller polling_interval".format(poll_interval,entry_min_str), err=True) exit(1) pfcwd_info['POLL_INTERVAL'] = poll_interval diff --git a/scripts/boot_part b/scripts/boot_part index 5bcae549c2..e9e51a9362 100755 --- a/scripts/boot_part +++ b/scripts/boot_part @@ -52,7 +52,7 @@ def print_partitions(blkdev): index = m.group(3) if name != blkdev or not index: continue - print index, label + print(index, label) ## Get the current boot partition index def get_boot_partition(blkdev): @@ -117,7 +117,7 @@ def main(): if cur is None: logger.error('Failed to get boot partition') return -1 - print 'Current rootfs partition is: {0}'.format(cur) + print('Current rootfs partition is: {0}'.format(cur)) ## Handle the command line if args.index is None: diff --git a/scripts/decode-syseeprom b/scripts/decode-syseeprom index bb542fd4a4..2dc892f2aa 100755 --- a/scripts/decode-syseeprom +++ b/scripts/decode-syseeprom @@ -92,7 +92,7 @@ def run(target, opts, args, support_eeprom_db): return 0 status = target.check_status() - if status <> 'ok': + if status != 'ok': sys.stderr.write("Device is not ready: " + status + "\n") exit(0) @@ -126,30 +126,30 @@ def run(target, opts, args, support_eeprom_db): if opts.init: err = target.update_eeprom_db(e) if err: - print "Failed to update eeprom database" + print("Failed to update eeprom database") return -1 elif opts.mgmtmac: mm = target.mgmtaddrstr(e) if mm != None: - print mm + print(mm) elif opts.serial: try: serial = target.serial_number_str(e) except NotImplementedError as e: - print e + print(e) else: - print serial or "Undefined." + print(serial or "Undefined.") elif opts.modelstr: mm = target.modelstr(e) if mm != None: - print mm + print(mm) else: target.decode_eeprom(e) (is_valid, valid_crc) = target.is_checksum_valid(e) if is_valid: - print '(checksum valid)' + print('(checksum valid)') else: - print '(*** checksum invalid)' + print('(*** checksum invalid)') # + ', should be 0x' + binascii.b2a_hex(array('I', [valid_crc])).upper() + ')' return 0 @@ -172,6 +172,6 @@ if __name__ == "__main__": except KeyboardInterrupt: sys.stderr.write("\nInterrupted\n") exit(1) - except (RuntimeError, OSError, IOError), errstr: + except (RuntimeError, OSError, IOError) as errstr: sys.stderr.write("%s : ERROR : %s\n" % (sys.argv[0], str(errstr))) exit(1) diff --git a/scripts/fast-reboot-dump.py b/scripts/fast-reboot-dump.py index 83387ad755..4a6a356d13 100644 --- a/scripts/fast-reboot-dump.py +++ b/scripts/fast-reboot-dump.py @@ -94,7 +94,7 @@ def get_map_bridge_port_id_2_iface_name(db): if port_id in port_id_2_iface: bridge_port_id_2_iface_name[bridge_port_id] = port_id_2_iface[port_id] else: - print "Not found" + print("Not found") return bridge_port_id_2_iface_name @@ -268,7 +268,7 @@ def main(): args = parser.parse_args() root_dir = args.target if not os.path.isdir(root_dir): - print "Target directory '%s' not found" % root_dir + print("Target directory '%s' not found" % root_dir) return 3 all_available_macs, map_mac_ip_per_vlan = generate_fdb_entries(root_dir + '/fdb.json') arp_entries = generate_arp_entries(root_dir + '/arp.json', all_available_macs) diff --git a/scripts/fdbclear b/scripts/fdbclear index de5d380bef..4b723cca55 100644 --- a/scripts/fdbclear +++ b/scripts/fdbclear @@ -49,7 +49,7 @@ def main(): fdb.send_notification("ALL", "ALL") print("FDB entries are cleared.") except Exception as e: - print e.message + print(e.message) sys.exit(1) if __name__ == "__main__": diff --git a/scripts/fdbshow b/scripts/fdbshow index 6743caf3cd..9f96fe7b1d 100755 --- a/scripts/fdbshow +++ b/scripts/fdbshow @@ -87,7 +87,7 @@ class FdbShow(object): vlan_id = port_util.get_vlan_id_from_bvid(self.db, fdb["bvid"]) except Exception: vlan_id = fdb["bvid"] - print "Failed to get Vlan id for bvid {}\n".format(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,)) self.bridge_mac_list.sort(key = lambda x: x[0]) @@ -129,8 +129,8 @@ class FdbShow(object): self.FDB_COUNT += 1 output.append([self.FDB_COUNT, fdb[0], fdb[1], fdb[2], fdb[3]]) - print tabulate(output, self.HEADER) - print "Total number of entries {0} ".format(self.FDB_COUNT) + print(tabulate(output, self.HEADER)) + print("Total number of entries {0} ".format(self.FDB_COUNT)) def main(): @@ -145,7 +145,7 @@ def main(): fdb = FdbShow() fdb.display(args.vlan, args.port) except Exception as e: - print e.message + print(e.message) sys.exit(1) if __name__ == "__main__": diff --git a/scripts/gearboxutil b/scripts/gearboxutil index c143ff744d..678b6b6484 100755 --- a/scripts/gearboxutil +++ b/scripts/gearboxutil @@ -123,7 +123,7 @@ class PhyStatus(object): # Sorting and tabulating the result table. sorted_table = natsorted(table) - print tabulate(sorted_table, phy_header_status, tablefmt="simple", stralign='right') + print(tabulate(sorted_table, phy_header_status, tablefmt="simple", stralign='right')) def __init__(self): self.appl_db = db_connect_appl() @@ -180,7 +180,7 @@ class InterfaceStatus(object): # Sorting and tabulating the result table. sorted_table = natsorted(table) - print tabulate(sorted_table, intf_header_status, tablefmt="simple", stralign='right') + print(tabulate(sorted_table, intf_header_status, tablefmt="simple", stralign='right')) def __init__(self): self.appl_db = db_connect_appl() @@ -201,17 +201,17 @@ def main(args): """ if len(args) == 0: - print "No valid arguments provided" + print("No valid arguments provided") return cmd1 = args[0] if cmd1 != "phys" and cmd1 != "interfaces": - print "No valid command provided" + print("No valid command provided") return cmd2 = args[1] if cmd2 != "status" and cmd2 != "counters": - print "No valid command provided" + print("No valid command provided") return if cmd1 == "phys" and cmd2 == "status": diff --git a/scripts/intfstat b/scripts/intfstat index 3591016b7e..6b5d8215f4 100755 --- a/scripts/intfstat +++ b/scripts/intfstat @@ -93,11 +93,11 @@ class Intfstat(object): if counter_rif_name_map is None: - print "No %s in the DB!" % COUNTERS_RIF_NAME_MAP + print("No %s in the DB!" % COUNTERS_RIF_NAME_MAP) sys.exit(1) if rif and not rif in counter_rif_name_map: - print "Interface %s missing from %s! Make sure it exists" % (rif, COUNTERS_RIF_NAME_MAP) + print("Interface %s missing from %s! Make sure it exists" % (rif, COUNTERS_RIF_NAME_MAP)) sys.exit(2) if rif: @@ -140,10 +140,10 @@ class Intfstat(object): data.tx_p_ok, STATUS_NA, STATUS_NA, data.tx_p_err)) if use_json: - print table_as_json(table, header) + print(table_as_json(table, header)) else: - print tabulate(table, header, tablefmt='simple', stralign='right') + print(tabulate(table, header, tablefmt='simple', stralign='right')) def cnstat_diff_print(self, cnstat_new_dict, cnstat_old_dict, use_json): """ @@ -182,9 +182,9 @@ class Intfstat(object): STATUS_NA, cntr.tx_p_err)) if use_json: - print table_as_json(table, header) + print(table_as_json(table, header)) else: - print tabulate(table, header, tablefmt='simple', stralign='right') + print(tabulate(table, header, tablefmt='simple', stralign='right')) def cnstat_single_interface(self, rif, cnstat_new_dict, cnstat_old_dict): @@ -218,8 +218,8 @@ class Intfstat(object): body = body % (cntr.rx_p_ok, cntr.rx_b_ok, cntr.rx_p_err,cntr.rx_b_err, cntr.tx_p_ok, cntr.tx_b_ok, cntr.tx_p_err, cntr.tx_b_err) - print header - print body + print(header) + print(body) def main(): @@ -276,7 +276,7 @@ def main(): os.rmdir(cnstat_dir) sys.exit(0) except IOError as e: - print e.errno, e + print(e.errno, e) sys.exit(e) if delete_saved_stats: @@ -284,7 +284,7 @@ def main(): os.remove(cnstat_fqn_file) except IOError as e: if e.errno != ENOENT: - print e.errno, e + print(e.errno, e) sys.exit(1) finally: if os.listdir(cnstat_dir) == []: @@ -299,7 +299,7 @@ def main(): try: os.makedirs(cnstat_dir) except IOError as e: - print e.errno, e + print(e.errno, e) sys.exit(1) if save_fresh_stats: @@ -308,24 +308,24 @@ def main(): except IOError as e: sys.exit(e.errno) else: - print "Cleared counters" + print("Cleared counters") sys.exit(0) if wait_time_in_seconds == 0: if os.path.isfile(cnstat_fqn_file): try: cnstat_cached_dict = pickle.load(open(cnstat_fqn_file, 'r')) - print "Last cached time was " + str(cnstat_cached_dict.get('time')) + print("Last cached time was " + str(cnstat_cached_dict.get('time'))) if interface_name: intfstat.cnstat_single_interface(interface_name, cnstat_dict, cnstat_cached_dict) else: intfstat.cnstat_diff_print(cnstat_dict, cnstat_cached_dict, use_json) except IOError as e: - print e.errno, e + print(e.errno, e) else: if tag_name: - print "\nFile '%s' does not exist" % cnstat_fqn_file - print "Did you run 'intfstat -c -t %s' to record the counters via tag %s?\n" % (tag_name, tag_name) + print("\nFile '%s' does not exist" % cnstat_fqn_file) + print("Did you run 'intfstat -c -t %s' to record the counters via tag %s?\n" % (tag_name, tag_name)) else: if interface_name: intfstat.cnstat_single_interface(interface_name, cnstat_dict, None) @@ -334,7 +334,7 @@ def main(): else: #wait for the specified time and then gather the new stats and output the difference. time.sleep(wait_time_in_seconds) - print "The rates are calculated within %s seconds period" % wait_time_in_seconds + print("The rates are calculated within %s seconds period" % wait_time_in_seconds) cnstat_new_dict = intfstat.get_cnstat(rif=interface_name) if interface_name: intfstat.cnstat_single_interface(interface_name, cnstat_new_dict, cnstat_dict) diff --git a/scripts/intfutil b/scripts/intfutil index f35702aa0c..af11c1322a 100755 --- a/scripts/intfutil +++ b/scripts/intfutil @@ -409,7 +409,7 @@ class IntfStatus(object): # Sorting and tabulating the result table. sorted_table = natsorted(table) - print tabulate(sorted_table, header_stat if not sub_intf_only else header_stat_sub_intf, tablefmt="simple", stralign='right') + print(tabulate(sorted_table, header_stat if not sub_intf_only else header_stat_sub_intf, tablefmt="simple", stralign='right')) def __init__(self, intf_name): @@ -494,7 +494,7 @@ class IntfDescription(object): # Sorting and tabulating the result table. sorted_table = natsorted(table) - print tabulate(sorted_table, header_desc, tablefmt="simple", stralign='right') + print(tabulate(sorted_table, header_desc, tablefmt="simple", stralign='right')) def __init__(self, intf_name): @@ -519,12 +519,12 @@ class IntfDescription(object): def main(args): if len(args) == 0: - print "No valid arguments provided" + print("No valid arguments provided") return command = args[0] if command != "status" and command != "description": - print "No valid command provided" + print("No valid command provided") return intf_name = args[1] if len(args) == 2 else None diff --git a/scripts/natclear b/scripts/natclear index 1a22f7f100..c18ec7ba58 100644 --- a/scripts/natclear +++ b/scripts/natclear @@ -57,14 +57,12 @@ def main(): nat = NatClear() if clear_translations: nat.send_entries_notification("ENTRIES", "ALL") - print "" - print("Dynamic NAT entries are cleared.") + print("\nDynamic NAT entries are cleared.") elif clear_statistics: nat.send_statistics_notification("STATISTICS", "ALL") - print "" - print("NAT statistics are cleared.") + print("\nNAT statistics are cleared.") except Exception as e: - print e.message + print(e.message) sys.exit(1) if __name__ == "__main__": diff --git a/scripts/natconfig b/scripts/natconfig index b9f7869e55..6a2467e21b 100644 --- a/scripts/natconfig +++ b/scripts/natconfig @@ -238,9 +238,9 @@ class NatConfig(object): for napt in self.static_napt_data: output.append([napt[0], napt[1], napt[2], napt[3], napt[4], napt[5], napt[6]]) - print "" - print tabulate(output, HEADER) - print "" + print() + print(tabulate(output, HEADER)) + print() def display_pool(self): """ @@ -253,9 +253,9 @@ class NatConfig(object): for nat in self.nat_pool_data: output.append([nat[0], nat[1], nat[2]]) - print "" - print tabulate(output, HEADER) - print "" + print() + print(tabulate(output, HEADER)) + print() def display_binding(self): """ @@ -268,9 +268,9 @@ class NatConfig(object): for nat in self.nat_binding_data: output.append([nat[0], nat[1], nat[2], nat[3], nat[4]]) - print "" - print tabulate(output, HEADER) - print "" + print() + print(tabulate(output, HEADER)) + print() def display_global(self): """ @@ -280,31 +280,31 @@ class NatConfig(object): global_data = self.config_db.get_entry('NAT_GLOBAL', 'Values') if global_data: - print "" + print() if 'admin_mode' in global_data: - print "Admin Mode :", global_data['admin_mode'] + print("Admin Mode :", global_data['admin_mode']) else: - print "Admin Mode : disabled" + print("Admin Mode : disabled") if 'nat_timeout' in global_data: - print "Global Timeout :", global_data['nat_timeout'], "secs" + print("Global Timeout :", global_data['nat_timeout'], "secs") else: - print "Global Timeout : 600 secs" + print("Global Timeout : 600 secs") if 'nat_tcp_timeout' in global_data: - print "TCP Timeout :", global_data['nat_tcp_timeout'], "secs" + print("TCP Timeout :", global_data['nat_tcp_timeout'], "secs") else: - print "TCP Timeout : 86400 secs" + print("TCP Timeout : 86400 secs") if 'nat_udp_timeout' in global_data: - print "UDP Timeout :", global_data['nat_udp_timeout'], "secs" + print("UDP Timeout :", global_data['nat_udp_timeout'], "secs") else: - print "UDP Timeout : 300 secs" - print "" + print("UDP Timeout : 300 secs") + print() else: - print "" - print "Admin Mode : disabled" - print "Global Timeout : 600 secs" - print "TCP Timeout : 86400 secs" - print "UDP Timeout : 300 secs" - print "" + print() + print("Admin Mode : disabled") + print("Global Timeout : 600 secs") + print("TCP Timeout : 86400 secs") + print("UDP Timeout : 300 secs") + print() return def display_nat_zone(self): @@ -318,9 +318,9 @@ class NatConfig(object): for nat in self.nat_zone_data: output.append([nat[0], nat[1]]) - print "" - print tabulate(output, HEADER) - print "" + print() + print(tabulate(output, HEADER)) + print() def main(): parser = argparse.ArgumentParser(description='Display the nat configuration information', @@ -366,7 +366,7 @@ def main(): nat.fetch_nat_zone() nat.display_nat_zone() except Exception as e: - print e.message + print(e.message) sys.exit(1) if __name__ == "__main__": diff --git a/scripts/natshow b/scripts/natshow index 02945a524b..74888f0a7f 100644 --- a/scripts/natshow +++ b/scripts/natshow @@ -329,19 +329,19 @@ class NatShow(object): totalEntries = int(self.static_nat_entries) + int(self.dynamic_nat_entries) + int(self.static_napt_entries) + int(self.dynamic_napt_entries) totalEntries += (int(self.static_twice_nat_entries) + int(self.dynamic_twice_nat_entries) + int(self.static_twice_napt_entries) + int(self.dynamic_twice_napt_entries)) - print "" - print "Static NAT Entries ..................... {}".format(self.static_nat_entries) - print "Static NAPT Entries ..................... {}".format(self.static_napt_entries) - print "Dynamic NAT Entries ..................... {}".format(self.dynamic_nat_entries) - print "Dynamic NAPT Entries ..................... {}".format(self.dynamic_napt_entries) - print "Static Twice NAT Entries ..................... {}".format(self.static_twice_nat_entries) - print "Static Twice NAPT Entries ..................... {}".format(self.static_twice_napt_entries) - print "Dynamic Twice NAT Entries ..................... {}".format(self.dynamic_twice_nat_entries) - print "Dynamic Twice NAPT Entries ..................... {}".format(self.dynamic_twice_napt_entries) - print "Total SNAT/SNAPT Entries ..................... {}".format(self.snat_entries) - print "Total DNAT/DNAPT Entries ..................... {}".format(self.dnat_entries) - print "Total Entries ..................... {}".format(totalEntries) - print "" + print() + print("Static NAT Entries ..................... {}".format(self.static_nat_entries)) + print("Static NAPT Entries ..................... {}".format(self.static_napt_entries)) + print("Dynamic NAT Entries ..................... {}".format(self.dynamic_nat_entries)) + print("Dynamic NAPT Entries ..................... {}".format(self.dynamic_napt_entries)) + print("Static Twice NAT Entries ..................... {}".format(self.static_twice_nat_entries)) + print("Static Twice NAPT Entries ..................... {}".format(self.static_twice_napt_entries)) + print("Dynamic Twice NAT Entries ..................... {}".format(self.dynamic_twice_nat_entries)) + print("Dynamic Twice NAPT Entries ..................... {}".format(self.dynamic_twice_napt_entries)) + print("Total SNAT/SNAPT Entries ..................... {}".format(self.snat_entries)) + print("Total DNAT/DNAPT Entries ..................... {}".format(self.dnat_entries)) + print("Total Entries ..................... {}".format(totalEntries)) + print() def display_translations(self): """ @@ -354,8 +354,8 @@ class NatShow(object): for nat in self.nat_entries_list: output.append([nat[0], nat[1], nat[2], nat[3], nat[4]]) - print tabulate(output, HEADER) - print "" + print(tabulate(output, HEADER)) + print() def display_statistics(self): """ @@ -368,9 +368,9 @@ class NatShow(object): for nat in self.nat_statistics_list: output.append([nat[0], nat[1], nat[2], nat[3], nat[4]]) - print "" - print tabulate(output, HEADER) - print "" + print() + print(tabulate(output, HEADER)) + print() def main(): parser = argparse.ArgumentParser(description='Display the nat information', @@ -409,7 +409,7 @@ def main(): nat.display_count() except Exception as e: - print e.message + print(e.message) sys.exit(1) if __name__ == "__main__": diff --git a/scripts/nbrshow b/scripts/nbrshow index b607070150..8d1abe7562 100644 --- a/scripts/nbrshow +++ b/scripts/nbrshow @@ -94,7 +94,7 @@ class NbrBase(object): vlan_id = port_util.get_vlan_id_from_bvid(self.db, fdb["bvid"]) except Exception: vlan_id = fdb["bvid"] - print "Failed to get Vlan id for bvid {}\n".format(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,)) return @@ -141,11 +141,11 @@ class NbrBase(object): self.nbrdata = natsorted(output, key=lambda x: x[0]) - print tabulate(self.nbrdata, self.HEADER) - print "Total number of entries {0} ".format(self.NBR_COUNT) + print(tabulate(self.nbrdata, self.HEADER)) + print("Total number of entries {0} ".format(self.NBR_COUNT)) def display_err(self): - print "Error fetching Neighbors: {} ".format(self.err) + print("Error fetching Neighbors: {} ".format(self.err)) class ArpShow(NbrBase): @@ -258,7 +258,7 @@ def main(): arp.display() except Exception as e: - print e.message + print(e.message) sys.exit(1) diff --git a/scripts/pcmping b/scripts/pcmping index 2ec42712d6..06fd61bfd1 100755 --- a/scripts/pcmping +++ b/scripts/pcmping @@ -48,7 +48,7 @@ def find_probe_packet(interface, dst_out, dst_in, sockets, exp_socket, max_iter) src_out = dst_in decap_valid = False for x in range(0, max_iter): - print "---------- Attempting to create probe packet that goes through %s, iteration: %d ---------" % (interface, x) + print("---------- Attempting to create probe packet that goes through %s, iteration: %d ---------" % (interface, x)) ip_src = socket.inet_ntoa(struct.pack('>I', random.randint(1, 0xffffffff))) ip_src =ipaddress.IPv4Address(unicode(ip_src,'utf-8')) while ip_src == ipaddress.IPv4Address(unicode(dst_in,'utf-8')) or \ @@ -70,10 +70,10 @@ def find_probe_packet(interface, dst_out, dst_in, sockets, exp_socket, max_iter) decap_valid = True if decap_valid: - print ("Decap works properly. link %s is unreachable, Please check!\n" % interface) + print("Decap works properly. link %s is unreachable, Please check!\n" % interface) sys.exit(0) else: - print ("Decap using %s doesn't work properly, Please Check!\n" % (dst_out)) + print("Decap using %s doesn't work properly, Please Check!\n" % (dst_out)) sys.exit(0) def get_portchannel(interface): @@ -126,8 +126,8 @@ def create_socket(interface, portchannel): return sockets, exp_socket def print_statistics(interface, total_count, recv_count): - print "\n--- %s ping statistics ---" % interface - print ("%d packets transmitted, %d received, %0.2f%% packet loss" % (total_count, recv_count, (total_count-recv_count)*1.0/total_count*100)) + print("\n--- %s ping statistics ---" % interface) + print("%d packets transmitted, %d received, %0.2f%% packet loss" % (total_count, recv_count, (total_count-recv_count)*1.0/total_count*100)) def main(): parser = argparse.ArgumentParser(description='Check portchannel member link state', @@ -156,8 +156,8 @@ def main(): portchannel_ip = get_portchannel_ipv4(portchannel_name) sockets, exp_socket = create_socket(interface, portchannel) pkt, exp_pkt = find_probe_packet(interface, decap_ip, portchannel_ip, sockets, exp_socket, max_trial) - print "Preparation done! Start probing ............" - print "PORTCHANNEL Member PING %d btyes of data. PORTCHANNEL: %s, INTERFACE: %s" % (PROBE_PACKET_LEN, portchannel_name, interface) + print("Preparation done! Start probing ............") + print("PORTCHANNEL Member PING %d btyes of data. PORTCHANNEL: %s, INTERFACE: %s" % (PROBE_PACKET_LEN, portchannel_name, interface)) recv_count = 0 total_count = 0 try: @@ -167,10 +167,10 @@ def main(): have_received, delay, recv_socket = receive(sockets, SELECT_TIMEOUT, exp_pkt, time_sent) total_count = total_count + 1 if have_received: - print "%d bytes from %s: time=%0.4fms" % (PROBE_PACKET_LEN, interface, delay) + print("%d bytes from %s: time=%0.4fms" % (PROBE_PACKET_LEN, interface, delay)) recv_count = recv_count + 1 else: - print "packet not received!" + print("packet not received!") if total_count == exp_count: break; time.sleep(1) diff --git a/scripts/pfcstat b/scripts/pfcstat index 106cdda84b..7649c07f4d 100755 --- a/scripts/pfcstat +++ b/scripts/pfcstat @@ -105,9 +105,9 @@ class Pfcstat(object): data.pfc6, data.pfc7)) if rx: - print tabulate(table, header_Rx, tablefmt='simple', stralign='right') + print(tabulate(table, header_Rx, tablefmt='simple', stralign='right')) else: - print tabulate(table, header_Tx, tablefmt='simple', stralign='right') + print(tabulate(table, header_Tx, tablefmt='simple', stralign='right')) def cnstat_diff_print(self, cnstat_new_dict, cnstat_old_dict, rx): """ @@ -150,9 +150,9 @@ class Pfcstat(object): cntr.pfc6, cntr.pfc7)) if rx: - print tabulate(table, header_Rx, tablefmt='simple', stralign='right') + print(tabulate(table, header_Rx, tablefmt='simple', stralign='right')) else: - print tabulate(table, header_Tx, tablefmt='simple', stralign='right') + print(tabulate(table, header_Tx, tablefmt='simple', stralign='right')) def main(): parser = argparse.ArgumentParser(description='Display the pfc counters', @@ -189,7 +189,7 @@ Examples: os.rmdir(cnstat_dir) sys.exit(0) except IOError as e: - print e.errno, e + print(e.errno, e) sys.exit(e) """ @@ -207,7 +207,7 @@ Examples: try: os.makedirs(cnstat_dir) except IOError as e: - print e.errno, e + print(e.errno, e) sys.exit(1) if save_fresh_stats: @@ -215,10 +215,10 @@ Examples: pickle.dump(cnstat_dict_rx, open(cnstat_fqn_file_rx, 'w')) pickle.dump(cnstat_dict_tx, open(cnstat_fqn_file_tx, 'w')) except IOError as e: - print e.errno, e + print(e.errno, e) sys.exit(e.errno) else: - print "Clear saved counters" + print("Clear saved counters") sys.exit(0) @@ -228,24 +228,25 @@ Examples: if os.path.isfile(cnstat_fqn_file_rx): try: cnstat_cached_dict = pickle.load(open(cnstat_fqn_file_rx, 'r')) - print "Last cached time was " + str(cnstat_cached_dict.get('time')) + print("Last cached time was " + str(cnstat_cached_dict.get('time'))) pfcstat.cnstat_diff_print(cnstat_dict_rx, cnstat_cached_dict, True) except IOError as e: - print e.errno, e + print(e.errno, e) else: pfcstat.cnstat_print(cnstat_dict_rx, True) - print + print() + """ Print the counters of pfc tx counter """ if os.path.isfile(cnstat_fqn_file_tx): try: cnstat_cached_dict = pickle.load(open(cnstat_fqn_file_tx, 'r')) - print "Last cached time was " + str(cnstat_cached_dict.get('time')) + print("Last cached time was " + str(cnstat_cached_dict.get('time'))) pfcstat.cnstat_diff_print(cnstat_dict_tx, cnstat_cached_dict, False) except IOError as e: - print e.errno, e + print(e.errno, e) else: pfcstat.cnstat_print(cnstat_dict_tx, False) diff --git a/scripts/portstat b/scripts/portstat index 42757d3677..b34191d0cd 100644 --- a/scripts/portstat +++ b/scripts/portstat @@ -167,9 +167,9 @@ class Portstat(object): data.tx_drop, data.tx_ovr)) if use_json: - print table_as_json(table, header) + print(table_as_json(table, header)) else: - print tabulate(table, header, tablefmt='simple', stralign='right') + print(tabulate(table, header, tablefmt='simple', stralign='right')) def cnstat_diff_print(self, cnstat_new_dict, cnstat_old_dict, intf_list, use_json, print_all, errors_only, rates_only): """ @@ -277,9 +277,9 @@ class Portstat(object): cntr.tx_ovr)) if use_json: - print table_as_json(table, header) + print(table_as_json(table, header)) else: - print tabulate(table, header, tablefmt='simple', stralign='right') + print(tabulate(table, header, tablefmt='simple', stralign='right')) def main(): @@ -341,7 +341,7 @@ Examples: os.rmdir(cnstat_dir) sys.exit(0) except IOError as e: - print e.errno, e + print(e.errno, e) sys.exit(e) if delete_saved_stats: @@ -349,7 +349,7 @@ Examples: os.remove(cnstat_fqn_file) except IOError as e: if e.errno != ENOENT: - print e.errno, e + print(e.errno, e) sys.exit(1) finally: if os.listdir(cnstat_dir) == []: @@ -372,7 +372,7 @@ Examples: try: os.makedirs(cnstat_dir) except IOError as e: - print e.errno, e + print(e.errno, e) sys.exit(1) @@ -382,7 +382,7 @@ Examples: except IOError as e: sys.exit(e.errno) else: - print "Cleared counters" + print("Cleared counters") sys.exit(0) if wait_time_in_seconds == 0: @@ -390,20 +390,20 @@ Examples: if os.path.isfile(cnstat_fqn_file): try: cnstat_cached_dict = pickle.load(open(cnstat_fqn_file, 'r')) - print "Last cached time was " + str(cnstat_cached_dict.get('time')) + print("Last cached time was " + str(cnstat_cached_dict.get('time'))) portstat.cnstat_diff_print(cnstat_dict, cnstat_cached_dict, intf_list, use_json, print_all, errors_only, rates_only) except IOError as e: - print e.errno, e + print(e.errno, e) else: if tag_name: - print "\nFile '%s' does not exist" % cnstat_fqn_file - print "Did you run 'portstat -c -t %s' to record the counters via tag %s?\n" % (tag_name, tag_name) + print("\nFile '%s' does not exist" % cnstat_fqn_file) + print("Did you run 'portstat -c -t %s' to record the counters via tag %s?\n" % (tag_name, tag_name)) else: portstat.cnstat_print(cnstat_dict, intf_list, use_json, print_all, errors_only, rates_only) else: #wait for the specified time and then gather the new stats and output the difference. time.sleep(wait_time_in_seconds) - print "The rates are calculated within %s seconds period" % wait_time_in_seconds + print("The rates are calculated within %s seconds period" % wait_time_in_seconds) cnstat_new_dict = portstat.get_cnstat() portstat.cnstat_diff_print(cnstat_new_dict, cnstat_dict, intf_list, use_json, print_all, errors_only, rates_only) diff --git a/scripts/psushow b/scripts/psushow index f61d8b405f..d74aee3a88 100755 --- a/scripts/psushow +++ b/scripts/psushow @@ -26,7 +26,7 @@ def psu_status_show(index): chassis_name = "chassis {}".format(chassis_num) num_psus = db.get(db.STATE_DB, 'CHASSIS_INFO|{}'.format(chassis_name), 'psu_num') if not num_psus: - print "Error! Failed to get the number of PSUs!" + print("Error! Failed to get the number of PSUs!") return -1 supported_psu = range(1, int(num_psus) + 1) @@ -42,8 +42,8 @@ def psu_status_show(index): msg = "" psu_name = "PSU {}".format(psu) if psu not in supported_psu: - print "Error! The {} is not available on the platform.\n" \ - "Number of supported PSU - {}.".format(psu_name, num_psus) + print("Error! The {} is not available on the platform.\n" + "Number of supported PSU - {}.".format(psu_name, num_psus)) continue presence = db.get(db.STATE_DB, 'PSU_INFO|{}'.format(psu_name), 'presence') if presence == 'true': @@ -55,7 +55,7 @@ def psu_status_show(index): status_table.append([psu_name, msg, led_status]) if status_table: - print tabulate(status_table, header, tablefmt="simple") + print(tabulate(status_table, header, tablefmt="simple")) return 0 def main(): @@ -76,7 +76,7 @@ Examples: if status_show: err = psu_status_show(psu_index) if err: - print "Error: fail to get psu status from state DB" + print("Error: fail to get psu status from state DB") sys.exit(1) if __name__ == "__main__": diff --git a/scripts/queuestat b/scripts/queuestat index 6b14581afd..9ce450a85d 100755 --- a/scripts/queuestat +++ b/scripts/queuestat @@ -56,7 +56,7 @@ class Queuestat(object): def get_queue_port(table_id): port_table_id = self.db.get(self.db.COUNTERS_DB, COUNTERS_QUEUE_PORT_MAP, table_id) if port_table_id is None: - print "Port is not available!", table_id + print("Port is not available!", table_id) sys.exit(1) return port_table_id @@ -64,7 +64,7 @@ class Queuestat(object): # Get all ports self.counter_port_name_map = self.db.get_all(self.db.COUNTERS_DB, COUNTERS_PORT_NAME_MAP) if self.counter_port_name_map is None: - print "COUNTERS_PORT_NAME_MAP is empty!" + print("COUNTERS_PORT_NAME_MAP is empty!") sys.exit(1) self.port_queues_map = {} @@ -77,7 +77,7 @@ class Queuestat(object): # Get Queues for each port counter_queue_name_map = self.db.get_all(self.db.COUNTERS_DB, COUNTERS_QUEUE_NAME_MAP) if counter_queue_name_map is None: - print "COUNTERS_QUEUE_NAME_MAP is empty!" + print("COUNTERS_QUEUE_NAME_MAP is empty!") sys.exit(1) for queue in counter_queue_name_map: @@ -95,7 +95,7 @@ class Queuestat(object): def get_queue_index(table_id): queue_index = self.db.get(self.db.COUNTERS_DB, COUNTERS_QUEUE_INDEX_MAP, table_id) if queue_index is None: - print "Queue index is not available!", table_id + print("Queue index is not available!", table_id) sys.exit(1) return queue_index @@ -103,7 +103,7 @@ class Queuestat(object): def get_queue_type(table_id): queue_type = self.db.get(self.db.COUNTERS_DB, COUNTERS_QUEUE_TYPE_MAP, table_id) if queue_type is None: - print "Queue Type is not available!", table_id + print("Queue Type is not available!", table_id) sys.exit(1) elif queue_type == SAI_QUEUE_TYPE_MULTICAST: return QUEUE_TYPE_MC @@ -112,7 +112,7 @@ class Queuestat(object): elif queue_type == SAI_QUEUE_TYPE_ALL: return QUEUE_TYPE_ALL else: - print "Queue Type is invalid:", table_id, queue_type + print("Queue Type is invalid:", table_id, queue_type) sys.exit(1) fields = ["0","0","0","0","0","0"] @@ -151,8 +151,8 @@ class Queuestat(object): data.totalpacket, data.totalbytes, data.droppacket, data.dropbytes)) - print tabulate(table, header, tablefmt='simple', stralign='right') - print + print(tabulate(table, header, tablefmt='simple', stralign='right')) + print() def cnstat_diff_print(self, port, cnstat_new_dict, cnstat_old_dict): """ @@ -188,8 +188,8 @@ class Queuestat(object): cntr.totalpacket, cntr.totalbytes, cntr.droppacket, cntr.dropbytes)) - print tabulate(table, header, tablefmt='simple', stralign='right') - print + print(tabulate(table, header, tablefmt='simple', stralign='right')) + print() def get_print_all_stat(self): # Get stat for each port @@ -200,16 +200,16 @@ class Queuestat(object): if os.path.isfile(cnstat_fqn_file_name): try: cnstat_cached_dict = pickle.load(open(cnstat_fqn_file_name, 'r')) - print port + " Last cached time was " + str(cnstat_cached_dict.get('time')) + print(port + " Last cached time was " + str(cnstat_cached_dict.get('time'))) self.cnstat_diff_print(port, cnstat_dict, cnstat_cached_dict) except IOError as e: - print e.errno, e + print(e.errno, e) else: self.cnstat_print(port, cnstat_dict) def get_print_port_stat(self, port): if not port in self.port_queues_map: - print "Port doesn't exist!", port + print("Port doesn't exist!", port) sys.exit(1) # Get stat for the port queried @@ -218,10 +218,10 @@ class Queuestat(object): if os.path.isfile(cnstat_fqn_file_name): try: cnstat_cached_dict = pickle.load(open(cnstat_fqn_file_name, 'r')) - print "Last cached time was " + str(cnstat_cached_dict.get('time')) + print("Last cached time was " + str(cnstat_cached_dict.get('time'))) self.cnstat_diff_print(port, cnstat_dict, cnstat_cached_dict) except IOError as e: - print e.errno, e + print(e.errno, e) else: self.cnstat_print(port, cnstat_dict) @@ -230,7 +230,7 @@ class Queuestat(object): try: os.makedirs(cnstat_dir) except IOError as e: - print e.errno, e + print(e.errno, e) sys.exit(1) # Get stat for each port and save @@ -239,10 +239,10 @@ class Queuestat(object): try: pickle.dump(cnstat_dict, open(cnstat_fqn_file + port, 'w')) except IOError as e: - print e.errno, e + print(e.errno, e) sys.exit(e.errno) else: - print "Clear and update saved counters for " + port + print("Clear and update saved counters for " + port) def main(): global cnstat_dir @@ -283,7 +283,7 @@ Examples: os.rmdir(cnstat_dir) sys.exit(0) except IOError as e: - print e.errno, e + print(e.errno, e) sys.exit(e) queuestat = Queuestat() diff --git a/scripts/sfpshow b/scripts/sfpshow index 875b64d8df..f77740ab2c 100755 --- a/scripts/sfpshow +++ b/scripts/sfpshow @@ -314,7 +314,7 @@ class SFPShow(object): out_put = out_put + '\n' - print out_put + click.echo(out_put) def display_presence(self, interfacename): port_table = [] diff --git a/scripts/sonic-kdump-config b/scripts/sonic-kdump-config index 4a0bba6273..696a87adc8 100755 --- a/scripts/sonic-kdump-config +++ b/scripts/sonic-kdump-config @@ -410,14 +410,14 @@ def cmd_kdump_num_dumps(verbose, num_dumps): ## Command: Display kdump status def cmd_kdump_status(): - print 'Kdump Administrative Mode: ', + print('Kdump Administrative Mode: ', end='') kdump_enabled = get_kdump_administrative_mode() if kdump_enabled: print('Enabled') else: print('Disabled') - print 'Kdump Operational State: ', + print('Kdump Operational State: ', end='') (rc, lines, err_str) = run_command("/usr/sbin/kdump-config status", use_shell=False); if len(lines) >= 1 and ": ready to kdump" in lines[0]: use_kdump_in_cfg = read_use_kdump() diff --git a/scripts/teamshow b/scripts/teamshow index e38bf5affc..54199895be 100755 --- a/scripts/teamshow +++ b/scripts/teamshow @@ -81,7 +81,7 @@ class Teamshow(object): p = subprocess.Popen(teamdctl_cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) (output, err) = p.communicate() rc = p.wait() - if rc == 0: + if rc == 0: self.teamsraw[self.get_team_id(team)] = output else: self.err = err @@ -138,7 +138,7 @@ class Teamshow(object): output = [] for team_id in natsorted(self.summary): output.append([team_id, 'PortChannel'+team_id, self.summary[team_id]['protocol'], self.summary[team_id]['ports']]) - print tabulate(output, header) + print(tabulate(output, header)) def main(): if os.geteuid() != 0: diff --git a/scripts/watermarkcfg b/scripts/watermarkcfg index dec6665d0b..9d2c6be35e 100644 --- a/scripts/watermarkcfg +++ b/scripts/watermarkcfg @@ -28,9 +28,9 @@ class Watermarkcfg(object): wm_info = configdb.get_entry('WATERMARK_TABLE', 'TELEMETRY_INTERVAL') if wm_info: - print '\nTelemetry interval: ' + wm_info['interval'] + ' second(s)\n' + print('\nTelemetry interval: ' + wm_info['interval'] + ' second(s)\n') else: - print '\nTelemetry interval 120 second(s)\n' + print('\nTelemetry interval 120 second(s)\n') def main(): diff --git a/scripts/watermarkstat b/scripts/watermarkstat index 8b567ea3b5..ead5b6e369 100644 --- a/scripts/watermarkstat +++ b/scripts/watermarkstat @@ -56,7 +56,7 @@ class Watermarkstat(object): def get_queue_type(table_id): queue_type = self.counters_db.get(self.counters_db.COUNTERS_DB, COUNTERS_QUEUE_TYPE_MAP, table_id) if queue_type is None: - print >> sys.stderr, "Queue Type is not available!", table_id + sys.stderr.write("Queue Type is not available in table '{}'".format(table_id)) sys.exit(1) elif queue_type == SAI_QUEUE_TYPE_MULTICAST: return QUEUE_TYPE_MC @@ -65,13 +65,13 @@ class Watermarkstat(object): elif queue_type == SAI_QUEUE_TYPE_ALL: return QUEUE_TYPE_ALL else: - print >> sys.stderr, "Queue Type is invalid:", table_id, queue_type + sys.stderr.write("Queue Type '{} in table '{}' is invalid".format(queue_type, table_id)) sys.exit(1) def get_queue_port(table_id): port_table_id = self.counters_db.get(self.counters_db.COUNTERS_DB, COUNTERS_QUEUE_PORT_MAP, table_id) if port_table_id is None: - print >> sys.stderr, "Port is not available!", table_id + sys.stderr.write("Port is not available in table '{}'".format(table_id)) sys.exit(1) return port_table_id @@ -79,7 +79,7 @@ class Watermarkstat(object): def get_pg_port(table_id): port_table_id = self.counters_db.get(self.counters_db.COUNTERS_DB, COUNTERS_PG_PORT_MAP, table_id) if port_table_id is None: - print >> sys.stderr, "Port is not available!", table_id + sys.stderr.write("Port is not available in table '{}'".format(table_id)) sys.exit(1) return port_table_id @@ -87,7 +87,7 @@ class Watermarkstat(object): # Get all ports self.counter_port_name_map = self.counters_db.get_all(self.counters_db.COUNTERS_DB, COUNTERS_PORT_NAME_MAP) if self.counter_port_name_map is None: - print >> sys.stderr, "COUNTERS_PORT_NAME_MAP is empty!" + sys.stderr.write("COUNTERS_PORT_NAME_MAP is empty!") sys.exit(1) self.port_uc_queues_map = {} @@ -104,7 +104,7 @@ class Watermarkstat(object): # Get Queues for each port counter_queue_name_map = self.counters_db.get_all(self.counters_db.COUNTERS_DB, COUNTERS_QUEUE_NAME_MAP) if counter_queue_name_map is None: - print >> sys.stderr, "COUNTERS_QUEUE_NAME_MAP is empty!" + sys.stderr.write("COUNTERS_QUEUE_NAME_MAP is empty!") sys.exit(1) for queue in counter_queue_name_map: @@ -118,7 +118,7 @@ class Watermarkstat(object): # Get PGs for each port counter_pg_name_map = self.counters_db.get_all(self.counters_db.COUNTERS_DB, COUNTERS_PG_NAME_MAP) if counter_pg_name_map is None: - print >> sys.stderr, "COUNTERS_PG_NAME_MAP is empty!" + sys.stderr.write("COUNTERS_PG_NAME_MAP is empty!") sys.exit(1) for pg in counter_pg_name_map: @@ -128,7 +128,7 @@ class Watermarkstat(object): # Get all buffer pools self.buffer_pool_name_to_oid_map = self.counters_db.get_all(self.counters_db.COUNTERS_DB, COUNTERS_BUFFER_POOL_NAME_MAP) if self.buffer_pool_name_to_oid_map is None: - print >> sys.stderr, "COUNTERS_BUFFER_POOL_NAME_MAP is empty!" + sys.stderr.write("COUNTERS_BUFFER_POOL_NAME_MAP is empty!") sys.exit(1) self.watermark_types = { @@ -160,7 +160,7 @@ class Watermarkstat(object): def get_queue_index(self, table_id): queue_index = self.counters_db.get(self.counters_db.COUNTERS_DB, COUNTERS_QUEUE_INDEX_MAP, table_id) if queue_index is None: - print >> sys.stderr, "Queue index is not available!", table_id + sys.stderr.write("Queue index is not available in table '{}'".format(table_id)) sys.exit(1) return queue_index @@ -168,14 +168,14 @@ class Watermarkstat(object): def get_pg_index(self, table_id): pg_index = self.counters_db.get(self.counters_db.COUNTERS_DB, COUNTERS_PG_INDEX_MAP, table_id) if pg_index is None: - print >> sys.stderr, "Priority group index is not available!", table_id + sys.stderr.write("Priority group index is not available in table '{}'".format(table_id)) sys.exit(1) return pg_index def build_header(self, wm_type): if wm_type is None: - print >> sys.stderr, "Header info is not available!" + sys.stderr.write("Header info is not available!") sys.exit(1) self.header_list = ['Port'] @@ -234,7 +234,7 @@ class Watermarkstat(object): table.append(tuple(row_data)) print(type["message"]) - print tabulate(table, self.header_list, tablefmt='simple', stralign='right') + print(tabulate(table, self.header_list, tablefmt='simple', stralign='right')) def send_clear_notification(self, data): msg = json.dumps(data, separators=(',', ':')) diff --git a/sfputil/main.py b/sfputil/main.py index 75a5f741eb..a9e9160fa0 100644 --- a/sfputil/main.py +++ b/sfputil/main.py @@ -126,14 +126,14 @@ def logical_port_name_to_physical_port_list(port_name): if platform_sfputil.is_logical_port(port_name): return platform_sfputil.get_logical_to_physical(port_name) else: - print "Error: Invalid port '%s'" % port_name + click.echo("Error: Invalid port '%s'" % port_name) return None else: return [int(port_name)] def print_all_valid_port_values(): - print "Valid values for port: %s\n" % str(platform_sfputil.logical) + click.echo("Valid values for port: %s\n" % str(platform_sfputil.logical)) # Returns multi-line string of pretty SFP port EEPROM data @@ -144,7 +144,7 @@ def port_eeprom_data_string_pretty(logical_port_name, dump_dom): physical_port_list = logical_port_name_to_physical_port_list(logical_port_name) if physical_port_list is None: - print "Error: No physical ports found for logical port '%s'" % logical_port_name + click.echo("Error: No physical ports found for logical port '%s'" % logical_port_name) return "" if len(physical_port_list) > 1: @@ -192,7 +192,7 @@ def port_eeprom_data_string_pretty_oneline(logical_port_name, physical_port_list = logical_port_name_to_physical_port_list(logical_port_name) if physical_port_list is None: - print "Error: No physical ports found for logical port '%s'" % logical_port_name + click.echo("Error: No physical ports found for logical port '%s'" % logical_port_name) return "" if len(physical_port_list) > 1: @@ -232,7 +232,7 @@ def port_eeprom_data_raw_string_pretty(logical_port_name): physical_port_list = logical_port_name_to_physical_port_list(logical_port_name) if physical_port_list is None: - print "Error: No physical ports found for logical port '%s'" % logical_port_name + click.echo("Error: No physical ports found for logical port '%s'" % logical_port_name) return "" if len(physical_port_list) > 1: @@ -295,7 +295,7 @@ def cli(): """sfputil - Command line utility for managing SFP transceivers""" if os.geteuid() != 0: - print "Root privileges are required for this operation" + click.echo("Root privileges are required for this operation") sys.exit(1) # Load platform-specific sfputil class @@ -335,7 +335,7 @@ def eeprom(port, dump_dom, oneline, raw): logical_port_list = platform_sfputil.logical else: if platform_sfputil.is_valid_sfputil_port(port) == 0: - print "Error: invalid port '%s'\n" % port + click.echo("Error: invalid port '%s'\n" % port) print_all_valid_port_values() sys.exit(4) @@ -360,7 +360,7 @@ def eeprom(port, dump_dom, oneline, raw): for logical_port_name in logical_port_list: output += port_eeprom_data_string_pretty(logical_port_name, dump_dom) - print output + click.echo(output) # 'presence' subcommand @@ -377,7 +377,7 @@ def presence(port): logical_port_list = platform_sfputil.logical else: if platform_sfputil.is_valid_sfputil_port(port) == 0: - print "Error: invalid port '%s'\n" % port + click.echo("Error: invalid port '%s'\n" % port) print_all_valid_port_values() sys.exit(4) @@ -389,7 +389,7 @@ def presence(port): physical_port_list = logical_port_name_to_physical_port_list(logical_port_name) if physical_port_list is None: - print "Error: No physical ports found for logical port '%s'" % logical_port_name + click.echo("Error: No physical ports found for logical port '%s'" % logical_port_name) return if len(physical_port_list) > 1: @@ -411,7 +411,7 @@ def presence(port): i += 1 - print tabulate(output_table, table_header, tablefmt="simple") + click.echo(tabulate(output_table, table_header, tablefmt="simple")) # 'lpmode' subcommand @@ -428,7 +428,7 @@ def lpmode(port): logical_port_list = platform_sfputil.logical else: if platform_sfputil.is_valid_sfputil_port(port) == 0: - print "Error: invalid port '%s'\n" % port + click.echo("Error: invalid port '%s'\n" % port) print_all_valid_port_values() sys.exit(4) @@ -440,7 +440,7 @@ def lpmode(port): physical_port_list = logical_port_name_to_physical_port_list(logical_port_name) if physical_port_list is None: - print "Error: No physical ports found for logical port '%s'" % logical_port_name + click.echo("Error: No physical ports found for logical port '%s'" % logical_port_name) return if len(physical_port_list) > 1: @@ -462,7 +462,7 @@ def lpmode(port): i += 1 - print tabulate(output_table, table_header, tablefmt='simple') + click.echo(tabulate(output_table, table_header, tablefmt='simple')) # 'lpmode' subgroup @@ -478,22 +478,22 @@ def set_lpmode(logical_port, enable): i = 1 if platform_sfputil.is_valid_sfputil_port(logical_port) == 0: - print "Error: invalid port '%s'\n" % logical_port + click.echo("Error: invalid port '%s'\n" % logical_port) print_all_valid_port_values() sys.exit(4) physical_port_list = logical_port_name_to_physical_port_list(logical_port) if physical_port_list is None: - print "Error: No physical ports found for logical port '%s'" % logical_port + click.echo("Error: No physical ports found for logical port '%s'" % logical_port) return if len(physical_port_list) > 1: ganged = True for physical_port in physical_port_list: - print "%s low-power mode for port %s... " % ( + click.echo("%s low-power mode for port %s... " % ( "Enabling" if enable else "Disabling", - get_physical_port_name(logical_port, i, ganged)), + get_physical_port_name(logical_port, i, ganged))) try: result = platform_sfputil.set_low_power_mode(physical_port, enable) @@ -502,9 +502,9 @@ def set_lpmode(logical_port, enable): sys.exit(5) if result: - print "OK" + click.echo("OK") else: - print "Failed" + click.echo("Failed") i += 1 @@ -534,20 +534,20 @@ def reset(port_name): i = 1 if platform_sfputil.is_valid_sfputil_port(port_name) == 0: - print "Error: invalid port '%s'\n" % port_name + click.echo("Error: invalid port '%s'\n" % port_name) print_all_valid_port_values() sys.exit(4) physical_port_list = logical_port_name_to_physical_port_list(port_name) if physical_port_list is None: - print "Error: No physical ports found for logical port '%s'" % port_name + click.echo("Error: No physical ports found for logical port '%s'" % port_name) return if len(physical_port_list) > 1: ganged = True for physical_port in physical_port_list: - print "Resetting port %s... " % get_physical_port_name(port_name, i, ganged), + click.echo("Resetting port %s... " % get_physical_port_name(port_name, i, ganged)) try: result = platform_sfputil.reset(physical_port) @@ -556,9 +556,9 @@ def reset(port_name): sys.exit(5) if result: - print "OK" + click.echo("OK") else: - print "Failed" + click.echo("Failed") i += 1 diff --git a/show/main.py b/show/main.py index 44399729ce..a6b522d8b4 100755 --- a/show/main.py +++ b/show/main.py @@ -1298,7 +1298,7 @@ def get_if_admin_state(iface): try: state_file = open(admin_file.format(iface), "r") except IOError as e: - print "Error: unable to open file: %s" % str(e) + print("Error: unable to open file: %s" % str(e)) return "error" content = state_file.readline().rstrip() @@ -1321,7 +1321,7 @@ def get_if_oper_state(iface): try: state_file = open(oper_file.format(iface), "r") except IOError as e: - print "Error: unable to open file: %s" % str(e) + print("Error: unable to open file: %s" % str(e)) return "error" oper_state = state_file.readline().rstrip() @@ -1394,7 +1394,7 @@ def interfaces(): for ifaddr in ifaddresses[1:]: data.append(["", "", ifaddr[1], ""]) - print tabulate(data, header, tablefmt="simple", stralign='left', missingval="") + print(tabulate(data, header, tablefmt="simple", stralign='left', missingval="")) # get bgp peering info def get_bgp_peer(): @@ -1536,7 +1536,7 @@ def interfaces(): data.append(["", "", ifaddr[1], admin + "/" + oper, neighbor_info[0][0], neighbor_info[0][1]]) neighbor_info.pop(0) - print tabulate(data, header, tablefmt="simple", stralign='left', missingval="") + print(tabulate(data, header, tablefmt="simple", stralign='left', missingval="")) # @@ -1955,7 +1955,7 @@ def ntp(verbose): ntp_server = line.split(" ")[1] ntp_servers.append(ntp_server) ntp_dict['NTP Servers'] = ntp_servers - print tabulate(ntp_dict, headers=ntp_dict.keys(), tablefmt="simple", stralign='left', missingval="") + print(tabulate(ntp_dict, headers=ntp_dict.keys(), tablefmt="simple", stralign='left', missingval="")) # 'syslog' subcommand ("show runningconfiguration syslog") @@ -1973,7 +1973,7 @@ def syslog(verbose): server = line[0][5:] syslog_servers.append(server) syslog_dict['Syslog Servers'] = syslog_servers - print tabulate(syslog_dict, headers=syslog_dict.keys(), tablefmt="simple", stralign='left', missingval="") + print(tabulate(syslog_dict, headers=syslog_dict.keys(), tablefmt="simple", stralign='left', missingval="")) # @@ -2147,7 +2147,7 @@ def services(): print("---------------------------") cmd = "sudo docker exec {} ps aux | sed '$d'".format(line.rstrip()) proc1 = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True) - print proc1.stdout.read() + print(proc1.stdout.read()) else: break diff --git a/show/mlnx.py b/show/mlnx.py index 6b0d304a27..3dae4e906f 100644 --- a/show/mlnx.py +++ b/show/mlnx.py @@ -95,7 +95,7 @@ def is_issu_status_enabled(): try: sai_xml_path = sai_profile_kvs['SAI_INIT_CONFIG_FILE'] except KeyError: - print >> sys.stderr, "Failed to get SAI XML from sai profile" + click.echo("Failed to get SAI XML from sai profile", err=True) sys.exit(1) # Get ISSU from SAI XML @@ -105,7 +105,7 @@ def is_issu_status_enabled(): try: root = ET.fromstring(sai_xml_content) except ET.ParseError: - print >> sys.stderr, "Failed to parse SAI xml" + click.echo("Failed to parse SAI xml", err=True) sys.exit(1) el = root.find('platform_info').find('issu-enabled') @@ -124,9 +124,9 @@ def sniffer_status(): for index in range(len(components)): enabled = sniffer_status_get(env_variable_strings[index]) if enabled is True: - print components[index] + " sniffer is enabled" + click.echo(components[index] + " sniffer is enabled") else: - print components[index] + " sniffer is disabled" + click.echo(components[index] + " sniffer is disabled") @mlnx.command('issu') @@ -135,5 +135,5 @@ def issu_status(): res = is_issu_status_enabled() - print 'ISSU is enabled' if res else 'ISSU is disabled' + click.echo('ISSU is enabled' if res else 'ISSU is disabled') diff --git a/ssdutil/main.py b/ssdutil/main.py index 94939d3480..7edd8ab66a 100755 --- a/ssdutil/main.py +++ b/ssdutil/main.py @@ -56,7 +56,7 @@ def is_number(s): # ==================== Entry point ==================== def ssdutil(): if os.geteuid() != 0: - print "Root privileges are required for this operation" + print("Root privileges are required for this operation") sys.exit(1) parser = argparse.ArgumentParser() @@ -67,14 +67,14 @@ def ssdutil(): ssd = import_ssd_api(args.device) - print "Device Model : {}".format(ssd.get_model()) + print("Device Model : {}".format(ssd.get_model())) if args.verbose: - print "Firmware : {}".format(ssd.get_firmware()) - print "Serial : {}".format(ssd.get_serial()) - print "Health : {}{}".format(ssd.get_health(), "%" if is_number(ssd.get_health()) else "") - print "Temperature : {}{}".format(ssd.get_temperature(), "C" if is_number(ssd.get_temperature()) else "") + print("Firmware : {}".format(ssd.get_firmware())) + print("Serial : {}".format(ssd.get_serial())) + print("Health : {}{}".format(ssd.get_health(), "%" if is_number(ssd.get_health()) else "")) + print("Temperature : {}{}".format(ssd.get_temperature(), "C" if is_number(ssd.get_temperature()) else "")) if args.vendor: - print ssd.get_vendor_output() + print(ssd.get_vendor_output()) if __name__ == '__main__': ssdutil() diff --git a/tests/config_test.py b/tests/config_test.py index e3c519da6a..023f41337a 100644 --- a/tests/config_test.py +++ b/tests/config_test.py @@ -56,8 +56,8 @@ def test_load_minigraph(self, get_cmd_module, setup_single_broacom_asic): (config, show) = get_cmd_module runner = CliRunner() result = runner.invoke(config.config.commands["load_minigraph"], ["-y"]) - print result.exit_code - print result.output + print(result.exit_code) + print(result.output) traceback.print_tb(result.exc_info[2]) assert result.exit_code == 0 assert "\n".join([ l.rstrip() for l in result.output.split('\n')]) == load_minigraph_command_output @@ -69,11 +69,11 @@ def test_load_minigraph_with_disabled_telemetry(self, get_cmd_module, setup_sing result = runner.invoke(config.config.commands["feature"].commands["state"], ["telemetry", "disabled"], obj=db) assert result.exit_code == 0 result = runner.invoke(show.cli.commands["feature"].commands["status"], ["telemetry"], obj=db) - print result.output + print(result.output) assert result.exit_code == 0 result = runner.invoke(config.config.commands["load_minigraph"], ["-y"], obj=db) - print result.exit_code - print result.output + print(result.exit_code) + print(result.output) assert result.exit_code == 0 assert "telemetry" not in result.output diff --git a/utilities_common/cli.py b/utilities_common/cli.py index bbbb6df471..9b9c2693c1 100644 --- a/utilities_common/cli.py +++ b/utilities_common/cli.py @@ -259,7 +259,7 @@ def is_port_router_interface(config_db, port): if port == intf[0]: return True - return False + return False def is_pc_router_interface(config_db, pc): """Check if portchannel is a router interface""" From 091b78af9dc717f87ea89ae7e608d4ca6e0e0312 Mon Sep 17 00:00:00 2001 From: Joe LeVeque Date: Tue, 11 Aug 2020 05:19:21 +0000 Subject: [PATCH 2/7] Remove unused import --- pfcwd/main.py | 1 - 1 file changed, 1 deletion(-) diff --git a/pfcwd/main.py b/pfcwd/main.py index 8d87053e2a..1856ff0f45 100644 --- a/pfcwd/main.py +++ b/pfcwd/main.py @@ -3,7 +3,6 @@ import click import swsssdk import os -import sys from tabulate import tabulate from natsort import natsorted From 7a9a5c772950b31bc555ede590cdaf4c85054815 Mon Sep 17 00:00:00 2001 From: Joe LeVeque Date: Tue, 11 Aug 2020 07:37:46 +0000 Subject: [PATCH 3/7] Remove extra space --- scripts/fdbshow | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/fdbshow b/scripts/fdbshow index 9f96fe7b1d..383a26ae9b 100755 --- a/scripts/fdbshow +++ b/scripts/fdbshow @@ -130,7 +130,7 @@ class FdbShow(object): output.append([self.FDB_COUNT, fdb[0], fdb[1], fdb[2], fdb[3]]) print(tabulate(output, self.HEADER)) - print("Total number of entries {0} ".format(self.FDB_COUNT)) + print("Total number of entries {0}".format(self.FDB_COUNT)) def main(): From 0c702ffd616ea01076aa8e34bb349d35789d88ac Mon Sep 17 00:00:00 2001 From: Joe LeVeque Date: Tue, 11 Aug 2020 07:55:01 +0000 Subject: [PATCH 4/7] Don't print newline --- sfputil/main.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/sfputil/main.py b/sfputil/main.py index a9e9160fa0..23c7f77905 100644 --- a/sfputil/main.py +++ b/sfputil/main.py @@ -491,9 +491,9 @@ def set_lpmode(logical_port, enable): ganged = True for physical_port in physical_port_list: - click.echo("%s low-power mode for port %s... " % ( + click.echo("{} low-power mode for port {}... ".format( "Enabling" if enable else "Disabling", - get_physical_port_name(logical_port, i, ganged))) + get_physical_port_name(logical_port, i, ganged)), nl=False) try: result = platform_sfputil.set_low_power_mode(physical_port, enable) From d1f43db7629eec742a42feb79f566ac7ec6ba0b3 Mon Sep 17 00:00:00 2001 From: Joe LeVeque Date: Tue, 11 Aug 2020 07:57:04 +0000 Subject: [PATCH 5/7] Don't print other newline --- sfputil/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/sfputil/main.py b/sfputil/main.py index 23c7f77905..7dfd56b1a5 100644 --- a/sfputil/main.py +++ b/sfputil/main.py @@ -547,7 +547,7 @@ def reset(port_name): ganged = True for physical_port in physical_port_list: - click.echo("Resetting port %s... " % get_physical_port_name(port_name, i, ganged)) + click.echo("Resetting port %s... " % get_physical_port_name(port_name, i, ganged), nl=False) try: result = platform_sfputil.reset(physical_port) From bf6faa66c330b4cab321b60d104f4816f5f482c3 Mon Sep 17 00:00:00 2001 From: Joe LeVeque Date: Tue, 11 Aug 2020 18:46:13 +0000 Subject: [PATCH 6/7] Address comments --- crm/main.py | 16 ++++++++-------- pfc/main.py | 8 ++++---- show/main.py | 4 ++-- 3 files changed, 14 insertions(+), 14 deletions(-) diff --git a/crm/main.py b/crm/main.py index 4388521def..33fbfb5de5 100644 --- a/crm/main.py +++ b/crm/main.py @@ -56,9 +56,9 @@ def show_thresholds(self, resource): else: click.echo('\nError! Could not get CRM configuration.') - click.echo('\n') + click.echo() click.echo(tabulate(data, headers=header, tablefmt="simple", missingval="")) - click.echo('\n') + click.echo() def show_resources(self, resource): """ @@ -82,9 +82,9 @@ def show_resources(self, resource): else: click.echo('\nCRM counters are not ready. They would be populated after the polling interval.') - click.echo('\n') + click.echo() click.echo(tabulate(data, headers=header, tablefmt="simple", missingval="")) - click.echo('\n') + click.echo() def show_acl_resources(self): """ @@ -108,9 +108,9 @@ def show_acl_resources(self): crm_stats['crm_stats_' + res + "_available"] ]) - click.echo('\n') + click.echo() click.echo(tabulate(data, headers=header, tablefmt="simple", missingval="")) - click.echo('\n') + click.echo() def show_acl_table_resources(self): """ @@ -136,9 +136,9 @@ def show_acl_table_resources(self): if ('crm_stats_' + res + '_used' in crm_stats) and ('crm_stats_' + res + '_available' in crm_stats): data.append([id, res, crm_stats['crm_stats_' + res + '_used'], crm_stats['crm_stats_' + res + '_available']]) - click.echo('\n') + click.echo() click.echo(tabulate(data, headers=header, tablefmt="simple", missingval="")) - click.echo('\n') + click.echo() @click.group() diff --git a/pfc/main.py b/pfc/main.py index 9a5c4b5e8f..856c16ce95 100644 --- a/pfc/main.py +++ b/pfc/main.py @@ -45,9 +45,9 @@ def showPfcAsym(interface): sorted_table = natsorted(table) - click.echo('\n') + click.echo() click.echo(tabulate(sorted_table, headers=header, tablefmt="simple", missingval="")) - click.echo('\n') + click.echo() def configPfcPrio(status, interface, priority): configdb = swsssdk.ConfigDBConnector() @@ -110,9 +110,9 @@ def showPfcPrio(interface): table.append([intf, entry.get('pfc_enable', 'N/A')]) sorted_table = natsorted(table) - click.echo('\n') + click.echo() click.echo(tabulate(sorted_table, headers=header, tablefmt="simple", missingval="")) - click.echo('\n') + click.echo() @click.group() def cli(): diff --git a/show/main.py b/show/main.py index a6b522d8b4..7cd562fd4d 100755 --- a/show/main.py +++ b/show/main.py @@ -2940,7 +2940,7 @@ def neighbors(): r = ["", ip, mac, intf] table.append(r) click.echo(tabulate(table, header)) - click.echo("\n") + click.echo() if not bool(vnet_intfs): click.echo(tabulate(table, header)) @@ -2973,7 +2973,7 @@ def all(): click.echo(tabulate(table, header)) - click.echo("\n") + click.echo() header = ['vnet name', 'prefix', 'endpoint', 'mac address', 'vni'] From 11b47c178fa9998e8c9bc83171faf56ed4656ca9 Mon Sep 17 00:00:00 2001 From: Joe LeVeque Date: Tue, 11 Aug 2020 19:56:46 +0000 Subject: [PATCH 7/7] Replace 'sys.stderr.write' with 'print' --- scripts/watermarkstat | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/scripts/watermarkstat b/scripts/watermarkstat index ead5b6e369..f306cd62e9 100644 --- a/scripts/watermarkstat +++ b/scripts/watermarkstat @@ -56,7 +56,7 @@ class Watermarkstat(object): def get_queue_type(table_id): queue_type = self.counters_db.get(self.counters_db.COUNTERS_DB, COUNTERS_QUEUE_TYPE_MAP, table_id) if queue_type is None: - sys.stderr.write("Queue Type is not available in table '{}'".format(table_id)) + print("Queue Type is not available in table '{}'".format(table_id), file=sys.stderr) sys.exit(1) elif queue_type == SAI_QUEUE_TYPE_MULTICAST: return QUEUE_TYPE_MC @@ -65,13 +65,13 @@ class Watermarkstat(object): elif queue_type == SAI_QUEUE_TYPE_ALL: return QUEUE_TYPE_ALL else: - sys.stderr.write("Queue Type '{} in table '{}' is invalid".format(queue_type, table_id)) + print("Queue Type '{} in table '{}' is invalid".format(queue_type, table_id), file=sys.stderr) sys.exit(1) def get_queue_port(table_id): port_table_id = self.counters_db.get(self.counters_db.COUNTERS_DB, COUNTERS_QUEUE_PORT_MAP, table_id) if port_table_id is None: - sys.stderr.write("Port is not available in table '{}'".format(table_id)) + print("Port is not available in table '{}'".format(table_id), file=sys.stderr) sys.exit(1) return port_table_id @@ -79,7 +79,7 @@ class Watermarkstat(object): def get_pg_port(table_id): port_table_id = self.counters_db.get(self.counters_db.COUNTERS_DB, COUNTERS_PG_PORT_MAP, table_id) if port_table_id is None: - sys.stderr.write("Port is not available in table '{}'".format(table_id)) + print("Port is not available in table '{}'".format(table_id), file=sys.stderr) sys.exit(1) return port_table_id @@ -87,7 +87,7 @@ class Watermarkstat(object): # Get all ports self.counter_port_name_map = self.counters_db.get_all(self.counters_db.COUNTERS_DB, COUNTERS_PORT_NAME_MAP) if self.counter_port_name_map is None: - sys.stderr.write("COUNTERS_PORT_NAME_MAP is empty!") + print("COUNTERS_PORT_NAME_MAP is empty!", file=sys.stderr) sys.exit(1) self.port_uc_queues_map = {} @@ -104,7 +104,7 @@ class Watermarkstat(object): # Get Queues for each port counter_queue_name_map = self.counters_db.get_all(self.counters_db.COUNTERS_DB, COUNTERS_QUEUE_NAME_MAP) if counter_queue_name_map is None: - sys.stderr.write("COUNTERS_QUEUE_NAME_MAP is empty!") + print("COUNTERS_QUEUE_NAME_MAP is empty!", file=sys.stderr) sys.exit(1) for queue in counter_queue_name_map: @@ -118,7 +118,7 @@ class Watermarkstat(object): # Get PGs for each port counter_pg_name_map = self.counters_db.get_all(self.counters_db.COUNTERS_DB, COUNTERS_PG_NAME_MAP) if counter_pg_name_map is None: - sys.stderr.write("COUNTERS_PG_NAME_MAP is empty!") + print("COUNTERS_PG_NAME_MAP is empty!", file=sys.stderr) sys.exit(1) for pg in counter_pg_name_map: @@ -128,7 +128,7 @@ class Watermarkstat(object): # Get all buffer pools self.buffer_pool_name_to_oid_map = self.counters_db.get_all(self.counters_db.COUNTERS_DB, COUNTERS_BUFFER_POOL_NAME_MAP) if self.buffer_pool_name_to_oid_map is None: - sys.stderr.write("COUNTERS_BUFFER_POOL_NAME_MAP is empty!") + print("COUNTERS_BUFFER_POOL_NAME_MAP is empty!", file=sys.stderr) sys.exit(1) self.watermark_types = { @@ -160,7 +160,7 @@ class Watermarkstat(object): def get_queue_index(self, table_id): queue_index = self.counters_db.get(self.counters_db.COUNTERS_DB, COUNTERS_QUEUE_INDEX_MAP, table_id) if queue_index is None: - sys.stderr.write("Queue index is not available in table '{}'".format(table_id)) + print("Queue index is not available in table '{}'".format(table_id), file=sys.stderr) sys.exit(1) return queue_index @@ -168,14 +168,14 @@ class Watermarkstat(object): def get_pg_index(self, table_id): pg_index = self.counters_db.get(self.counters_db.COUNTERS_DB, COUNTERS_PG_INDEX_MAP, table_id) if pg_index is None: - sys.stderr.write("Priority group index is not available in table '{}'".format(table_id)) + print("Priority group index is not available in table '{}'".format(table_id), file=sys.stderr) sys.exit(1) return pg_index def build_header(self, wm_type): if wm_type is None: - sys.stderr.write("Header info is not available!") + print("Header info is not available!", file=sys.stderr) sys.exit(1) self.header_list = ['Port']