提交 cb27f0c7 编写于 作者: A Alessio Sergi

No more Python 2.6 compatible string.format calls

上级 28eb3f68
......@@ -100,8 +100,8 @@ def main():
Run it...
"""
# Log Glances and PSutil version
logger.info('Start Glances {0}'.format(__version__))
logger.info('{0} {1} and PSutil {2} detected'.format(
logger.info('Start Glances {}'.format(__version__))
logger.info('{} {} and PSutil {} detected'.format(
platform.python_implementation(),
platform.python_version(),
psutil_version))
......@@ -172,7 +172,7 @@ def main():
server = GlancesServer(cached_time=core.cached_time,
config=core.get_config(),
args=args)
print('Glances server is running on {0}:{1}'.format(args.bind_address, args.port))
print('Glances server is running on {}:{}'.format(args.bind_address, args.port))
# Set the server login/password (if -P/--password tag)
if args.password != "":
......
......@@ -77,10 +77,8 @@ class GlancesActions(object):
# Action already executed => Exit
return False
logger.debug("Run action {0} for {1} ({2}) with stats {3}".format(commands,
stat_name,
criticity,
mustache_dict))
logger.debug("Run action {} for {} ({}) with stats {}".format(
commands, stat_name, criticity, mustache_dict))
# Run all actions in background
for cmd in commands:
......@@ -90,12 +88,12 @@ class GlancesActions(object):
else:
cmd_full = cmd
# Execute the action
logger.info("Action triggered for {0} ({1}): {2}".format(stat_name, criticity, cmd_full))
logger.debug("Stats value for the trigger: {0}".format(mustache_dict))
logger.info("Action triggered for {} ({}): {}".format(stat_name, criticity, cmd_full))
logger.debug("Stats value for the trigger: {}".format(mustache_dict))
try:
Popen(cmd_full, shell=True)
except OSError as e:
logger.error("Can't execute the action ({0})".format(e))
logger.error("Can't execute the action ({})".format(e))
self.set(stat_name, criticity)
......
......@@ -48,7 +48,7 @@ class GlancesAmp(object):
def __init__(self, name=None, args=None):
"""Init AMP classe."""
logger.debug("Init {0} version {1}".format(self.NAME, self.VERSION))
logger.debug("Init {} version {}".format(self.NAME, self.VERSION))
# AMP name (= module name without glances_)
if name is None:
......@@ -86,7 +86,7 @@ class GlancesAmp(object):
amp_section = 'amp_' + self.amp_name
if (hasattr(config, 'has_section') and
config.has_section(amp_section)):
logger.debug("{0}: Load configuration".format(self.NAME))
logger.debug("{}: Load configuration".format(self.NAME))
for param, _ in config.items(amp_section):
try:
self.configs[param] = config.get_float_value(amp_section, param)
......@@ -94,9 +94,9 @@ class GlancesAmp(object):
self.configs[param] = config.get_value(amp_section, param).split(',')
if len(self.configs[param]) == 1:
self.configs[param] = self.configs[param][0]
logger.debug("{0}: Load parameter: {1} = {2}".format(self.NAME, param, self.configs[param]))
logger.debug("{}: Load parameter: {} = {}".format(self.NAME, param, self.configs[param]))
else:
logger.debug("{0}: Can not find section {1} in the configuration file".format(self.NAME, self.amp_name))
logger.debug("{}: Can not find section {} in the configuration file".format(self.NAME, self.amp_name))
return False
# enable, regex and refresh are mandatories
......@@ -104,10 +104,10 @@ class GlancesAmp(object):
if self.enable():
for k in ['regex', 'refresh']:
if k not in self.configs:
logger.warning("{0}: Can not find configuration key {1} in section {2}".format(self.NAME, k, self.amp_name))
logger.warning("{}: Can not find configuration key {} in section {}".format(self.NAME, k, self.amp_name))
self.configs['enable'] = 'false'
else:
logger.warning("{0} is disabled".format(self.NAME))
logger.warning("{} is disabled".format(self.NAME))
# Init the count to 0
self.configs['count'] = 0
......
......@@ -59,11 +59,11 @@ class Amp(GlancesAmp):
def update(self, process_list):
"""Update the AMP"""
# Get the systemctl status
logger.debug('{0}: Update stats using service {1}'.format(self.NAME, self.get('service_cmd')))
logger.debug('{}: Update stats using service {}'.format(self.NAME, self.get('service_cmd')))
try:
res = self.get('command')
except OSError as e:
logger.debug('{0}: Error while executing service ({1})'.format(self.NAME, e))
logger.debug('{}: Error while executing service ({})'.format(self.NAME, e))
else:
if res is not None:
msg = u(check_output(res.split(), stderr=STDOUT))
......@@ -71,7 +71,7 @@ class Amp(GlancesAmp):
else:
# Set the default message if command return None
# Default sum of CPU and MEM for the matching regex
self.set_result('CPU: {0:.1f}% | MEM: {1:.1f}%'.format(
self.set_result('CPU: {:.1f}% | MEM: {:.1f}%'.format(
sum([p['cpu_percent'] for p in process_list]),
sum([p['memory_percent'] for p in process_list])))
......
......@@ -76,12 +76,12 @@ class Amp(GlancesAmp):
def update(self, process_list):
"""Update the AMP"""
# Get the Nginx status
logger.debug('{0}: Update stats using status URL {1}'.format(self.NAME, self.get('status_url')))
logger.debug('{}: Update stats using status URL {}'.format(self.NAME, self.get('status_url')))
res = requests.get(self.get('status_url'))
if res.ok:
# u'Active connections: 1 \nserver accepts handled requests\n 1 1 1 \nReading: 0 Writing: 1 Waiting: 0 \n'
self.set_result(res.text.rstrip())
else:
logger.debug('{0}: Can not grab status URL {1} ({2})'.format(self.NAME, self.get('status_url'), res.reason))
logger.debug('{}: Can not grab status URL {} ({})'.format(self.NAME, self.get('status_url'), res.reason))
return self.result()
......@@ -68,11 +68,11 @@ class Amp(GlancesAmp):
def update(self, process_list):
"""Update the AMP"""
# Get the systemctl status
logger.debug('{0}: Update stats using systemctl {1}'.format(self.NAME, self.get('systemctl_cmd')))
logger.debug('{}: Update stats using systemctl {}'.format(self.NAME, self.get('systemctl_cmd')))
try:
res = check_output(self.get('systemctl_cmd').split())
except OSError as e:
logger.debug('{0}: Error while executing systemctl ({1})'.format(self.NAME, e))
logger.debug('{}: Error while executing systemctl ({})'.format(self.NAME, e))
else:
status = {}
# For each line
......@@ -89,7 +89,7 @@ class Amp(GlancesAmp):
# Build the output (string) message
output = 'Services\n'
for k, v in iteritems(status):
output += '{0}: {1}\n'.format(k, v)
output += '{}: {}\n'.format(k, v)
self.set_result(output, separator=' ')
return self.result()
......@@ -67,11 +67,11 @@ class Amp(GlancesAmp):
def update(self, process_list):
"""Update the AMP"""
# Get the systemctl status
logger.debug('{0}: Update stats using service {1}'.format(self.NAME, self.get('service_cmd')))
logger.debug('{}: Update stats using service {}'.format(self.NAME, self.get('service_cmd')))
try:
res = check_output(self.get('service_cmd').split(), stderr=STDOUT)
except OSError as e:
logger.debug('{0}: Error while executing service ({1})'.format(self.NAME, e))
logger.debug('{}: Error while executing service ({})'.format(self.NAME, e))
else:
status = {'running': 0, 'stopped': 0, 'upstart': 0}
# For each line
......@@ -89,7 +89,7 @@ class Amp(GlancesAmp):
# Build the output (string) message
output = 'Services\n'
for k, v in iteritems(status):
output += '{0}: {1}\n'.format(k, v)
output += '{}: {}\n'.format(k, v)
self.set_result(output, separator=' ')
return self.result()
......@@ -70,9 +70,9 @@ class AmpsList(object):
try:
amp = __import__(os.path.basename(amp_script)[:-3])
except ImportError as e:
logger.warning("Can not load {0}, you need to install an external Python package ({1})".format(os.path.basename(amp_script), e))
logger.warning("Cannot load {}, you need to install an external Python package ({})".format(os.path.basename(amp_script), e))
except Exception as e:
logger.warning("Can not load {0} ({1})".format(os.path.basename(amp_script), e))
logger.warning("Cannot load {} ({})".format(os.path.basename(amp_script), e))
else:
# Add the AMP to the dictionary
# The key is the AMP name
......@@ -82,7 +82,7 @@ class AmpsList(object):
# Load the AMP configuration
self.__amps_dict[amp_conf_name].load_config(self.config)
# Log AMPs list
logger.debug("AMPs' list: {0}".format(self.getList()))
logger.debug("AMPs list: {}".format(self.getList()))
return True
......
......@@ -41,7 +41,7 @@ except ImportError:
if zeroconf_tag:
zeroconf_min_version = (0, 17, 0)
zeroconf_version = tuple([int(num) for num in __zeroconf_version.split('.')])
logger.debug("Zeroconf version {0} detected.".format(__zeroconf_version))
logger.debug("Zeroconf version {} detected.".format(__zeroconf_version))
if zeroconf_version < zeroconf_min_version:
logger.critical("Please install zeroconf 0.17 or higher.")
sys.exit(1)
......@@ -191,7 +191,7 @@ class GlancesAutoDiscoverClient(object):
try:
self.zeroconf = Zeroconf()
except socket.error as e:
logger.error("Cannot start zeroconf: {0}".format(e))
logger.error("Cannot start zeroconf: {}".format(e))
# XXX *BSDs: Segmentation fault (core dumped)
# -- https://bitbucket.org/al45tair/netifaces/issues/15
......@@ -205,15 +205,15 @@ class GlancesAutoDiscoverClient(object):
pass
self.info = ServiceInfo(
zeroconf_type, '{0}:{1}.{2}'.format(hostname, args.port, zeroconf_type),
zeroconf_type, '{}:{}.{}'.format(hostname, args.port, zeroconf_type),
address=socket.inet_aton(zeroconf_bind_address), port=args.port,
weight=0, priority=0, properties={}, server=hostname)
try:
self.zeroconf.register_service(self.info)
except socket.error as e:
logger.error("Error while announcing Glances server: {0}".format(e))
logger.error("Error while announcing Glances server: {}".format(e))
else:
print("Announce the Glances server on the LAN (using {0} IP address)".format(zeroconf_bind_address))
print("Announce the Glances server on the LAN (using {} IP address)".format(zeroconf_bind_address))
else:
logger.error("Cannot announce Glances server on the network: zeroconf library not found.")
......
......@@ -55,11 +55,11 @@ class GlancesClient(object):
# Build the URI
if args.password != "":
self.uri = 'http://{0}:{1}@{2}:{3}'.format(args.username, args.password,
args.client, args.port)
self.uri = 'http://{}:{}@{}:{}'.format(args.username, args.password,
args.client, args.port)
else:
self.uri = 'http://{0}:{1}'.format(args.client, args.port)
logger.debug("Try to connect to {0}".format(self.uri))
self.uri = 'http://{}:{}'.format(args.client, args.port)
logger.debug("Try to connect to {}".format(self.uri))
# Try to connect to the URI
transport = GlancesClientTransport()
......@@ -68,7 +68,7 @@ class GlancesClient(object):
try:
self.client = ServerProxy(self.uri, transport=transport)
except Exception as e:
self.log_and_exit("Client couldn't create socket {0}: {1}".format(self.uri, e))
self.log_and_exit("Client couldn't create socket {}: {}".format(self.uri, e))
def log_and_exit(self, msg=''):
"""Log and exit."""
......@@ -100,7 +100,7 @@ class GlancesClient(object):
except socket.error as err:
# Fallback to SNMP
self.client_mode = 'snmp'
logger.error("Connection to Glances server failed ({0} {1})".format(err.errno, err.strerror))
logger.error("Connection to Glances server failed ({} {})".format(err.errno, err.strerror))
fallbackmsg = 'No Glances server found on {}. Trying fallback to SNMP...'.format(self.uri)
if not self.return_to_browser:
print(fallbackmsg)
......@@ -112,7 +112,7 @@ class GlancesClient(object):
if err.errcode == 401:
msg += " (Bad username/password)"
else:
msg += " ({0} {1})".format(err.errcode, err.errmsg)
msg += " ({} {})".format(err.errcode, err.errmsg)
self.log_and_exit(msg)
return False
......@@ -122,10 +122,10 @@ class GlancesClient(object):
# Init stats
self.stats = GlancesStatsClient(config=self.config, args=self.args)
self.stats.set_plugins(json.loads(self.client.getAllPlugins()))
logger.debug("Client version: {0} / Server version: {1}".format(__version__, client_version))
logger.debug("Client version: {} / Server version: {}".format(__version__, client_version))
else:
self.log_and_exit("Client and server not compatible: \
Client version: {0} / Server version: {1}".format(__version__, client_version))
Client version: {} / Server version: {}".format(__version__, client_version))
return False
return True
......@@ -180,7 +180,7 @@ class GlancesClient(object):
return self.update_snmp()
else:
self.end()
logger.critical("Unknown server mode: {0}".format(self.client_mode))
logger.critical("Unknown server mode: {}".format(self.client_mode))
sys.exit(2)
def update_glances(self):
......
......@@ -85,10 +85,10 @@ class GlancesClientBrowser(object):
clear_password = self.password.get_password(server['name'])
if clear_password is not None:
server['password'] = self.password.sha256_hash(clear_password)
return 'http://{0}:{1}@{2}:{3}'.format(server['username'], server['password'],
server['ip'], server['port'])
return 'http://{}:{}@{}:{}'.format(server['username'], server['password'],
server['ip'], server['port'])
else:
return 'http://{0}:{1}'.format(server['ip'], server['port'])
return 'http://{}:{}'.format(server['ip'], server['port'])
def __serve_forever(self):
"""Main client loop."""
......@@ -118,20 +118,20 @@ class GlancesClientBrowser(object):
s = ServerProxy(uri, transport=t)
except Exception as e:
logger.warning(
"Client browser couldn't create socket {0}: {1}".format(uri, e))
"Client browser couldn't create socket {}: {}".format(uri, e))
else:
# Mandatory stats
try:
# CPU%
cpu_percent = 100 - json.loads(s.getCpu())['idle']
v['cpu_percent'] = '{0:.1f}'.format(cpu_percent)
v['cpu_percent'] = '{:.1f}'.format(cpu_percent)
# MEM%
v['mem_percent'] = json.loads(s.getMem())['percent']
# OS (Human Readable name)
v['hr_name'] = json.loads(s.getSystem())['hr_name']
except (socket.error, Fault, KeyError) as e:
logger.debug(
"Error while grabbing stats form {0}: {1}".format(uri, e))
"Error while grabbing stats form {}: {}".format(uri, e))
v['status'] = 'OFFLINE'
except ProtocolError as e:
if e.errcode == 401:
......@@ -141,7 +141,7 @@ class GlancesClientBrowser(object):
v['status'] = 'PROTECTED'
else:
v['status'] = 'OFFLINE'
logger.debug("Cannot grab stats from {0} ({1} {2})".format(uri, e.errcode, e.errmsg))
logger.debug("Cannot grab stats from {} ({} {})".format(uri, e.errcode, e.errmsg))
else:
# Status
v['status'] = 'ONLINE'
......@@ -150,10 +150,10 @@ class GlancesClientBrowser(object):
try:
# LOAD
load_min5 = json.loads(s.getLoad())['min5']
v['load_min5'] = '{0:.2f}'.format(load_min5)
v['load_min5'] = '{:.2f}'.format(load_min5)
except Exception as e:
logger.warning(
"Error while grabbing stats form {0}: {1}".format(uri, e))
"Error while grabbing stats form {}: {}".format(uri, e))
# List can change size during iteration...
except RuntimeError:
logger.debug(
......@@ -165,12 +165,12 @@ class GlancesClientBrowser(object):
self.screen.update(self.get_servers_list())
else:
# Display the Glances client for the selected server
logger.debug("Selected server: {0}".format(self.get_servers_list()[self.screen.active_server]))
logger.debug("Selected server: {}".format(self.get_servers_list()[self.screen.active_server]))
# Connection can take time
# Display a popup
self.screen.display_popup(
'Connect to {0}:{1}'.format(v['name'], v['port']), duration=1)
'Connect to {}:{}'.format(v['name'], v['port']), duration=1)
# A password is needed to access to the server's stats
if self.get_servers_list()[self.screen.active_server]['password'] is None:
......@@ -181,13 +181,13 @@ class GlancesClientBrowser(object):
# Else, the password should be enter by the user
# Display a popup to enter password
clear_password = self.screen.display_popup(
'Password needed for {0}: '.format(v['name']), is_input=True)
'Password needed for {}: '.format(v['name']), is_input=True)
# Store the password for the selected server
if clear_password is not None:
self.set_in_selected('password', self.password.sha256_hash(clear_password))
# Display the Glance client on the selected server
logger.info("Connect Glances client to the {0} server".format(
logger.info("Connect Glances client to the {} server".format(
self.get_servers_list()[self.screen.active_server]['key']))
# Init the client
......@@ -203,7 +203,7 @@ class GlancesClientBrowser(object):
# Test if client and server are in the same major version
if not client.login():
self.screen.display_popup(
"Sorry, cannot connect to '{0}'\n"
"Sorry, cannot connect to '{}'\n"
"See 'glances.log' for more details".format(v['name']))
# Set the ONLINE status for the selected server
......@@ -214,7 +214,7 @@ class GlancesClientBrowser(object):
connection_type = client.serve_forever()
try:
logger.debug("Disconnect Glances client from the {0} server".format(
logger.debug("Disconnect Glances client from the {} server".format(
self.get_servers_list()[self.screen.active_server]['key']))
except IndexError:
# Server did not exist anymore
......
......@@ -98,9 +98,9 @@ class Config(object):
with open(config_file, encoding='utf-8') as f:
self.parser.read_file(f)
self.parser.read(f)
logger.info("Read configuration file '{0}'".format(config_file))
logger.info("Read configuration file '{}'".format(config_file))
except UnicodeDecodeError as err:
logger.error("Cannot decode configuration file '{0}': {1}".format(config_file, err))
logger.error("Cannot decode configuration file '{}': {}".format(config_file, err))
sys.exit(1)
# Save the loaded configuration file path (issue #374)
self._loaded_config_file = config_file
......
......@@ -47,10 +47,10 @@ class Export(GlancesExport):
self.csv_file = open(self.csv_filename, 'wb')
self.writer = csv.writer(self.csv_file)
except IOError as e:
logger.critical("Cannot create the CSV file: {0}".format(e))
logger.critical("Cannot create the CSV file: {}".format(e))
sys.exit(2)
logger.info("Stats exported to CSV file: {0}".format(self.csv_filename))
logger.info("Stats exported to CSV file: {}".format(self.csv_filename))
self.export_enable = True
......@@ -78,7 +78,7 @@ class Export(GlancesExport):
for stat in all_stats[i]:
# First line: header
if self.first_line:
csv_header += ('{0}_{1}_{2}'.format(
csv_header += ('{}_{}_{}'.format(
plugin, self.get_item_key(stat), item) for item in stat)
# Others lines: stats
csv_data += itervalues(stat)
......@@ -86,7 +86,7 @@ class Export(GlancesExport):
# First line: header
if self.first_line:
fieldnames = iterkeys(all_stats[i])
csv_header += ('{0}_{1}'.format(plugin, fieldname)
csv_header += ('{}_{}'.format(plugin, fieldname)
for fieldname in fieldnames)
# Others lines: stats
csv_data += itervalues(all_stats[i])
......
......@@ -73,7 +73,7 @@ class Export(GlancesExport):
return None
try:
es = Elasticsearch(hosts=['{0}:{1}'.format(self.host, self.port)])
es = Elasticsearch(hosts=['{}:{}'.format(self.host, self.port)])
except Exception as e:
logger.critical("Cannot connect to ElasticSearch server %s:%s (%s)" % (self.host, self.port, e))
sys.exit(2)
......@@ -93,7 +93,7 @@ class Export(GlancesExport):
def export(self, name, columns, points):
"""Write the points to the ES server."""
logger.debug("Export {0} stats to ElasticSearch".format(name))
logger.debug("Export {} stats to ElasticSearch".format(name))
# Create DB input
# http://elasticsearch-py.readthedocs.org/en/master/helpers.html
......@@ -114,4 +114,4 @@ class Export(GlancesExport):
try:
helpers.bulk(self.client, actions)
except Exception as e:
logger.error("Cannot export {0} stats to ElasticSearch ({1})".format(name, e))
logger.error("Cannot export {} stats to ElasticSearch ({})".format(name, e))
......@@ -71,7 +71,7 @@ class GlancesExport(object):
try:
ret = item[item['key']]
except KeyError:
logger.error("No 'key' available in {0}".format(item))
logger.error("No 'key' available in {}".format(item))
if isinstance(ret, list):
return ret[0]
else:
......@@ -136,7 +136,7 @@ class GlancesExport(object):
# Stats is a dict
# Is there a key ?
if 'key' in iterkeys(stats):
pre_key = '{0}.'.format(stats[stats['key']])
pre_key = '{}.'.format(stats[stats['key']])
else:
pre_key = ''
# Walk through the dict
......
......@@ -120,7 +120,7 @@ class Export(GlancesExport):
if self.db in get_all_db:
logger.info(
"Stats will be exported to InfluxDB server: {0}".format(db._baseurl))
"Stats will be exported to InfluxDB server: {}".format(db._baseurl))
else:
logger.critical("InfluxDB database '%s' did not exist. Please create it" % self.db)
sys.exit(2)
......@@ -129,7 +129,7 @@ class Export(GlancesExport):
def export(self, name, columns, points):
"""Write the points to the InfluxDB server."""
logger.debug("Export {0} stats to InfluxDB".format(name))
logger.debug("Export {} stats to InfluxDB".format(name))
# Manage prefix
if self.prefix is not None:
name = self.prefix + '.' + name
......@@ -152,4 +152,4 @@ class Export(GlancesExport):
try:
self.client.write_points(data)
except Exception as e:
logger.error("Cannot export {0} stats to InfluxDB ({1})".format(name, e))
logger.error("Cannot export {} stats to InfluxDB ({})".format(name, e))
......@@ -103,14 +103,14 @@ class Export(GlancesExport):
for i in range(len(columns)):
if not isinstance(points[i], Number):
continue
stat_name = '{0}.{1}.{2}'.format(self.prefix, name, columns[i])
stat_name = '{}.{}.{}'.format(self.prefix, name, columns[i])
stat_value = points[i]
tags = self.parse_tags(self.tags)
try:
self.client.send(stat_name, stat_value, **tags)
except Exception as e:
logger.error("Can not export stats %s to OpenTSDB (%s)" % (name, e))
logger.debug("Export {0} stats to OpenTSDB".format(name))
logger.debug("Export {} stats to OpenTSDB".format(name))
def exit(self):
"""Close the OpenTSDB export module."""
......
......@@ -89,10 +89,10 @@ class Export(GlancesExport):
for i in range(len(columns)):
if not isinstance(points[i], Number):
continue
stat_name = '{0}.{1}'.format(name, columns[i])
stat_name = '{}.{}'.format(name, columns[i])
stat_value = points[i]
try:
self.client.gauge(stat_name, stat_value)
except Exception as e:
logger.error("Can not export stats to Statsd (%s)" % e)
logger.debug("Export {0} stats to Statsd".format(name))
logger.debug("Export {} stats to Statsd".format(name))
......@@ -88,13 +88,13 @@ class GlancesFilter(object):
self._filter_re = None
if self.filter is not None:
logger.info("Set filter to {0} on key {1}".format(self.filter, self.filter_key))
logger.info("Set filter to {} on key {}".format(self.filter, self.filter_key))
# Compute the regular expression
try:
self._filter_re = re.compile(self.filter)
logger.debug("Filter regex compilation OK: {0}".format(self.filter))
logger.debug("Filter regex compilation OK: {}".format(self.filter))
except Exception as e:
logger.error("Cannot compile filter regex: {0} ({1})".format(self.filter, e))
logger.error("Cannot compile filter regex: {} ({})".format(self.filter, e))
self._filter = None
self._filter_re = None
self._filter_key = None
......
......@@ -84,7 +84,7 @@ class FolderList(object):
try:
value['path'] = self.config.get_value(section, key + 'path')
except Exception as e:
logger.error("Cannot read folder list: {0}".format(e))
logger.error("Cannot read folder list: {}".format(e))
continue
if value['path'] is None:
continue
......@@ -95,7 +95,7 @@ class FolderList(object):
value[i] = self.config.get_value(section, key + i)
except:
value[i] = None
logger.debug("No {0} threshold for folder {1}".format(i, value["path"]))
logger.debug("No {} threshold for folder {}".format(i, value["path"]))
# Add the item to the list
self.__folder_list.append(value)
......@@ -154,7 +154,7 @@ class FolderList(object):
try:
self.__folder_list[i]['size'] = self.__folder_size(self.path(i))
except Exception as e:
logger.debug('Can get folder size ({0}). Error: {1}'.format(self.path(i), e))
logger.debug('Cannot get folder size ({}). Error: {}'.format(self.path(i), e))
if e.errno == 13:
# Permission denied
self.__folder_list[i]['size'] = '!'
......
......@@ -90,9 +90,9 @@ def tempfile_name():
"""Return the tempfile name (full path)."""
ret = os.path.join(tempfile.gettempdir(), 'glances.log')
if os.access(ret, os.F_OK) and not os.access(ret, os.W_OK):
print("WARNING: Couldn't write to log file {0} (Permission denied)".format(ret))
print("WARNING: Couldn't write to log file {} (Permission denied)".format(ret))
ret = tempfile.mkstemp(prefix='glances', suffix='.log', text=True)
print("Create a new log file: {0}".format(ret[1]))
print("Create a new log file: {}".format(ret[1]))
return ret[1]
return ret
......
......@@ -177,7 +177,7 @@ Start the client browser (browser mode):\n\
parser.add_argument('--disable-autodiscover', action='store_true', default=False,
dest='disable_autodiscover', help='disable autodiscover feature')
parser.add_argument('-p', '--port', default=None, type=int, dest='port',
help='define the client/server TCP port [default: {0}]'.format(self.server_port))
help='define the client/server TCP port [default: {}]'.format(self.server_port))
parser.add_argument('-B', '--bind', default='0.0.0.0', dest='bind_address',
help='bind server to the given IPv4/IPv6 address or hostname')
parser.add_argument('--username', action='store_true', default=False, dest='username_prompt',
......@@ -197,7 +197,7 @@ Start the client browser (browser mode):\n\
parser.add_argument('--snmp-force', action='store_true', default=False,
dest='snmp_force', help='force SNMP mode')
parser.add_argument('-t', '--time', default=self.refresh_time, type=float,
dest='time', help='set refresh time in seconds [default: {0} sec]'.format(self.refresh_time))
dest='time', help='set refresh time in seconds [default: {} sec]'.format(self.refresh_time))
parser.add_argument('-w', '--webserver', action='store_true', default=False,
dest='webserver', help='run Glances in web server mode (bottle needed)')
# Display options
......@@ -280,17 +280,17 @@ Start the client browser (browser mode):\n\
# Interactive or file password
if args.server:
args.password = self.__get_password(
description='Define the Glances server password ({0} username): '.format(args.username),
description='Define the Glances server password ({} username): '.format(args.username),
confirm=True,
username=args.username)
elif args.webserver:
args.password = self.__get_password(
description='Define the Glances webserver password ({0} username): '.format(args.username),
description='Define the Glances webserver password ({} username): '.format(args.username),
confirm=True,
username=args.username)
elif args.client:
args.password = self.__get_password(
description='Enter the Glances server password ({0} username): '.format(args.username),
description='Enter the Glances server password ({} username): '.format(args.username),
clear=True,
username=args.username)
else:
......@@ -339,9 +339,9 @@ Start the client browser (browser mode):\n\
# Check graph output path
if args.enable_history and args.path_history is not None:
if not os.access(args.path_history, os.W_OK):
logger.critical("History output path {0} do not exist or is not writable".format(args.path_history))
logger.critical("History output path {} do not exist or is not writable".format(args.path_history))
sys.exit(2)
logger.debug("History output path is set to {0}".format(args.path_history))
logger.debug("History output path is set to {}".format(args.path_history))
# Disable HDDTemp if sensors are disabled
if args.disable_sensors:
......
......@@ -60,7 +60,7 @@ class Outdated(object):
}
# Read the configuration file
self.load_config(config)
logger.debug("Check Glances version up-to-date: {0}".format(not self.args.disable_check_update))
logger.debug("Check Glances version up-to-date: {}".format(not self.args.disable_check_update))
# And update !
self.get_pypi_version()
......@@ -73,7 +73,7 @@ class Outdated(object):
config.has_section(global_section)):
self.args.disable_check_update = config.get_value(global_section, 'check_update').lower() == 'false'
else:
logger.debug("Can not find section {0} in the configuration file".format(global_section))
logger.debug("Cannot find section {} in the configuration file".format(global_section))
return False
return True
......@@ -118,7 +118,7 @@ class Outdated(object):
logger.debug("Python Request lib is not installed. Can not get last Glances version on Pypi.")
return False
logger.debug("Check Glances version (installed: {0} / latest: {1})".format(self.installed_version(), self.latest_version()))
logger.debug("Check Glances version (installed: {} / latest: {})".format(self.installed_version(), self.latest_version()))
return LooseVersion(self.latest_version()) > LooseVersion(self.installed_version())
def _load_cache(self):
......@@ -129,7 +129,7 @@ class Outdated(object):
with open(os.path.join(self._cache_path(), 'glances-version.db'), 'rb') as f:
cached_data = pickle.load(f)
except Exception as e:
logger.debug("Can not read the version cache file ({0})".format(e))
logger.debug("Cannot read the version cache file ({})".format(e))
else:
logger.debug("Read the version cache file")
if cached_data['installed_version'] != self.installed_version() or \
......@@ -165,7 +165,7 @@ class Outdated(object):
def _update_pypi_version(self):
"""Get the latest Pypi version (as a string) via the Restful JSON API"""
# Get the Nginx status
logger.debug("Get latest Glances version from the Pypi Restfull API ({0})".format(self.PYPI_API_URL))
logger.debug("Get latest Glances version from the PyPI RESTful API ({})".format(self.PYPI_API_URL))
# Update the current time
self.data[u'refresh_date'] = datetime.now()
......@@ -173,14 +173,14 @@ class Outdated(object):
try:
res = requests.get(self.PYPI_API_URL)
except Exception as e:
logger.debug("Can not get the Glances version from the Pypi Restfull API ({0})".format(e))
logger.debug("Cannot get the Glances version from the PyPI RESTful API ({})".format(e))
else:
if res.ok:
# Update data
self.data[u'latest_version'] = json.loads(res.text)['info']['version']
logger.debug("Save Glances version to the cache file")
else:
logger.debug("Can not get the Glances version from the Pypi Restfull API ({0})".format(res.reason))
logger.debug("Cannot get the Glances version from the PyPI RESTful API ({})".format(res.reason))
# Save result to the cache file
# Note: also saved if the Glances Pypi version can not be grabed
......
......@@ -95,5 +95,5 @@ class Bar(object):
whole += 1
ret += self.__empty_char * int(self.size - whole)
if self.__with_text:
ret = '{0}{1:>5}%'.format(ret, self.percent)
ret = '{}{:>5}%'.format(ret, self.percent)
return ret
......@@ -104,7 +104,7 @@ class GlancesBottle(object):
self.plugins_list = self.stats.getAllPlugins()
# Bind the Bottle TCP address/port
bindmsg = 'Glances web server started on http://{0}:{1}/'.format(self.args.bind_address, self.args.port)
bindmsg = 'Glances web server started on http://{}:{}/'.format(self.args.bind_address, self.args.port)
logger.info(bindmsg)
print(bindmsg)
self._app.run(host=self.args.bind_address, port=self.args.port, quiet=not self.args.debug)
......
......@@ -107,7 +107,7 @@ class _GlancesCurses(object):
if config.has_section('outputs'):
logger.debug('Read the outputs section in the configuration file')
self.theme['name'] = config.get_value('outputs', 'curse_theme', default='black')
logger.debug('Theme for the curse interface: {0}'.format(self.theme['name']))
logger.debug('Theme for the curse interface: {}'.format(self.theme['name']))
def is_theme(self, name):
'''Return True if the theme *name* should be used'''
......@@ -572,7 +572,7 @@ class _GlancesCurses(object):
max_processes_displayed = 0
if (glances_processes.max_processes is None or
glances_processes.max_processes != max_processes_displayed):
logger.debug("Set number of displayed processes to {0}".format(max_processes_displayed))
logger.debug("Set number of displayed processes to {}".format(max_processes_displayed))
glances_processes.max_processes = max_processes_displayed
stats_processlist = stats.get_plugin(
......@@ -758,10 +758,10 @@ class _GlancesCurses(object):
# Generate history graph
if self.history_tag and self.args.enable_history:
self.display_popup(
'Generate graphs history in {0}\nPlease wait...'.format(
'Generate graphs history in {}\nPlease wait...'.format(
self.glances_history.get_output_folder()))
self.display_popup(
'Generate graphs history in {0}\nDone: {1} graphs generated'.format(
'Generate graphs history in {}\nDone: {} graphs generated'.format(
self.glances_history.get_output_folder(),
self.glances_history.generate_graph(stats)))
elif self.reset_history_tag and self.args.enable_history:
......
......@@ -106,7 +106,7 @@ class GlancesCursesBrowser(_GlancesCurses):
sys.exit(0)
elif self.pressedkey == 10:
# 'ENTER' > Run Glances on the selected server
logger.debug("Server number {0} selected".format(self.cursor + 1))
logger.debug("Server number {} selected".format(self.cursor + 1))
self.active_server = self.cursor
elif self.pressedkey == 65:
# 'UP' > Up in the server list
......@@ -126,7 +126,7 @@ class GlancesCursesBrowser(_GlancesCurses):
servers_list: Dict of dict with servers stats
"""
# Flush display
logger.debug('Servers list: {0}'.format(servers_list))
logger.debug('Servers list: {}'.format(servers_list))
self.flush(servers_list)
# Wait
......@@ -182,7 +182,7 @@ class GlancesCursesBrowser(_GlancesCurses):
elif len(servers_list) == 1:
msg = 'One Glances server available'
else:
msg = '{0} Glances servers available'.format(len(servers_list))
msg = '{} Glances servers available'.format(len(servers_list))
if self.args.disable_autodiscover:
msg += ' ' + '(auto discover is disabled)'
self.term_window.addnstr(y, x,
......@@ -238,7 +238,7 @@ class GlancesCursesBrowser(_GlancesCurses):
server_stat[c[0]] = v[c[0]]
except KeyError as e:
logger.debug(
"Cannot grab stats {0} from server (KeyError: {1})".format(c[0], e))
"Cannot grab stats {} from server (KeyError: {})".format(c[0], e))
server_stat[c[0]] = '?'
# Display alias instead of name
try:
......
......@@ -101,7 +101,7 @@ class GlancesPassword(object):
"""
if os.path.exists(self.password_filepath) and not clear:
# If the password file exist then use it
logger.info("Read password from file {0}".format(self.password_filepath))
logger.info("Read password from file {}".format(self.password_filepath))
password = self.load_password()
else:
# password_sha256 is the plain SHA-256 password
......@@ -138,7 +138,7 @@ class GlancesPassword(object):
try:
os.makedirs(self.password_path)
except OSError as e:
logger.error("Cannot create Glances directory: {0}".format(e))
logger.error("Cannot create Glances directory: {}".format(e))
return
# Create/overwrite the password file
......
......@@ -74,7 +74,7 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg, "TITLE"))
logs_len = glances_logs.len()
if logs_len > 1:
msg = ' (last {0} entries)'.format(logs_len)
msg = ' (last {} entries)'.format(logs_len)
else:
msg = ' (one entry)'
ret.append(self.curse_add_line(msg, "TITLE"))
......@@ -88,8 +88,8 @@ class Plugin(GlancesPlugin):
# Duration
if alert[1] > 0:
# If finished display duration
msg = ' ({0})'.format(datetime.fromtimestamp(alert[1]) -
datetime.fromtimestamp(alert[0]))
msg = ' ({})'.format(datetime.fromtimestamp(alert[1]) -
datetime.fromtimestamp(alert[0]))
else:
msg = ' (ongoing)'
ret.append(self.curse_add_line(msg))
......@@ -97,22 +97,22 @@ class Plugin(GlancesPlugin):
# Infos
if alert[1] > 0:
# If finished do not display status
msg = '{0} on {1}'.format(alert[2], alert[3])
msg = '{} on {}'.format(alert[2], alert[3])
ret.append(self.curse_add_line(msg))
else:
msg = str(alert[3])
ret.append(self.curse_add_line(msg, decoration=alert[2]))
# Min / Mean / Max
if self.approx_equal(alert[6], alert[4], tolerance=0.1):
msg = ' ({0:.1f})'.format(alert[5])
msg = ' ({:.1f})'.format(alert[5])
else:
msg = ' (Min:{0:.1f} Mean:{1:.1f} Max:{2:.1f})'.format(
msg = ' (Min:{:.1f} Mean:{:.1f} Max:{:.1f})'.format(
alert[6], alert[5], alert[4])
ret.append(self.curse_add_line(msg))
# Top processes
top_process = ', '.join([p['name'] for p in alert[9]])
if top_process != '':
msg = ': {0}'.format(top_process)
msg = ': {}'.format(top_process)
ret.append(self.curse_add_line(msg))
return ret
......
......@@ -106,15 +106,15 @@ class Plugin(GlancesPlugin):
if m['result'] is None:
continue
# Display AMP
first_column = '{0}'.format(m['name'])
first_column = '{}'.format(m['name'])
first_column_style = self.get_alert(m['count'], m['countmin'], m['countmax'])
second_column = '{0}'.format(m['count'])
second_column = '{}'.format(m['count'])
for l in m['result'].split('\n'):
# Display first column with the process name...
msg = '{0:<16} '.format(first_column)
msg = '{:<16} '.format(first_column)
ret.append(self.curse_add_line(msg, first_column_style))
# ... and second column with the number of matching processes...
msg = '{0:<4} '.format(second_column)
msg = '{:<4} '.format(second_column)
ret.append(self.curse_add_line(msg))
# ... only on the first line
first_column = second_column = ''
......
......@@ -226,10 +226,10 @@ class Plugin(GlancesPlugin):
idle_tag = 'user' not in self.stats
# Header
msg = '{0:8}'.format('CPU')
msg = '{:8}'.format('CPU')
ret.append(self.curse_add_line(msg, "TITLE"))
# Total CPU usage
msg = '{0:>5}%'.format(self.stats['total'])
msg = '{:>5}%'.format(self.stats['total'])
if idle_tag:
ret.append(self.curse_add_line(
msg, self.get_views(key='total', option='decoration')))
......@@ -237,15 +237,15 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg))
# Nice CPU
if 'nice' in self.stats:
msg = ' {0:8}'.format('nice:')
msg = ' {:8}'.format('nice:')
ret.append(self.curse_add_line(msg, optional=self.get_views(key='nice', option='optional')))
msg = '{0:>5}%'.format(self.stats['nice'])
msg = '{:>5}%'.format(self.stats['nice'])
ret.append(self.curse_add_line(msg, optional=self.get_views(key='nice', option='optional')))
# ctx_switches
if 'ctx_switches' in self.stats:
msg = ' {0:8}'.format('ctx_sw:')
msg = ' {:8}'.format('ctx_sw:')
ret.append(self.curse_add_line(msg, optional=self.get_views(key='ctx_switches', option='optional')))
msg = '{0:>5}'.format(int(self.stats['ctx_switches'] // self.stats['time_since_update']))
msg = '{:>5}'.format(int(self.stats['ctx_switches'] // self.stats['time_since_update']))
ret.append(self.curse_add_line(
msg, self.get_views(key='ctx_switches', option='decoration'),
optional=self.get_views(key='ctx_switches', option='optional')))
......@@ -254,80 +254,80 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_new_line())
# User CPU
if 'user' in self.stats:
msg = '{0:8}'.format('user:')
msg = '{:8}'.format('user:')
ret.append(self.curse_add_line(msg))
msg = '{0:>5}%'.format(self.stats['user'])
msg = '{:>5}%'.format(self.stats['user'])
ret.append(self.curse_add_line(
msg, self.get_views(key='user', option='decoration')))
elif 'idle' in self.stats:
msg = '{0:8}'.format('idle:')
msg = '{:8}'.format('idle:')
ret.append(self.curse_add_line(msg))
msg = '{0:>5}%'.format(self.stats['idle'])
msg = '{:>5}%'.format(self.stats['idle'])
ret.append(self.curse_add_line(msg))
# IRQ CPU
if 'irq' in self.stats:
msg = ' {0:8}'.format('irq:')
msg = ' {:8}'.format('irq:')
ret.append(self.curse_add_line(msg, optional=self.get_views(key='irq', option='optional')))
msg = '{0:>5}%'.format(self.stats['irq'])
msg = '{:>5}%'.format(self.stats['irq'])
ret.append(self.curse_add_line(msg, optional=self.get_views(key='irq', option='optional')))
# interrupts
if 'interrupts' in self.stats:
msg = ' {0:8}'.format('inter:')
msg = ' {:8}'.format('inter:')
ret.append(self.curse_add_line(msg, optional=self.get_views(key='interrupts', option='optional')))
msg = '{0:>5}'.format(int(self.stats['interrupts'] // self.stats['time_since_update']))
msg = '{:>5}'.format(int(self.stats['interrupts'] // self.stats['time_since_update']))
ret.append(self.curse_add_line(msg, optional=self.get_views(key='interrupts', option='optional')))
# New line
ret.append(self.curse_new_line())
# System CPU
if 'system' in self.stats and not idle_tag:
msg = '{0:8}'.format('system:')
msg = '{:8}'.format('system:')
ret.append(self.curse_add_line(msg))
msg = '{0:>5}%'.format(self.stats['system'])
msg = '{:>5}%'.format(self.stats['system'])
ret.append(self.curse_add_line(
msg, self.get_views(key='system', option='decoration')))
else:
msg = '{0:8}'.format('core:')
msg = '{:8}'.format('core:')
ret.append(self.curse_add_line(msg))
msg = '{0:>6}'.format(self.stats['nb_log_core'])
msg = '{:>6}'.format(self.stats['nb_log_core'])
ret.append(self.curse_add_line(msg))
# IOWait CPU
if 'iowait' in self.stats:
msg = ' {0:8}'.format('iowait:')
msg = ' {:8}'.format('iowait:')
ret.append(self.curse_add_line(msg, optional=self.get_views(key='iowait', option='optional')))
msg = '{0:>5}%'.format(self.stats['iowait'])
msg = '{:>5}%'.format(self.stats['iowait'])
ret.append(self.curse_add_line(
msg, self.get_views(key='iowait', option='decoration'),
optional=self.get_views(key='iowait', option='optional')))
# soft_interrupts
if 'soft_interrupts' in self.stats:
msg = ' {0:8}'.format('sw_int:')
msg = ' {:8}'.format('sw_int:')
ret.append(self.curse_add_line(msg, optional=self.get_views(key='soft_interrupts', option='optional')))
msg = '{0:>5}'.format(int(self.stats['soft_interrupts'] // self.stats['time_since_update']))
msg = '{:>5}'.format(int(self.stats['soft_interrupts'] // self.stats['time_since_update']))
ret.append(self.curse_add_line(msg, optional=self.get_views(key='soft_interrupts', option='optional')))
# New line
ret.append(self.curse_new_line())
# Idle CPU
if 'idle' in self.stats and not idle_tag:
msg = '{0:8}'.format('idle:')
msg = '{:8}'.format('idle:')
ret.append(self.curse_add_line(msg))
msg = '{0:>5}%'.format(self.stats['idle'])
msg = '{:>5}%'.format(self.stats['idle'])
ret.append(self.curse_add_line(msg))
# Steal CPU usage
if 'steal' in self.stats:
msg = ' {0:8}'.format('steal:')
msg = ' {:8}'.format('steal:')
ret.append(self.curse_add_line(msg, optional=self.get_views(key='steal', option='optional')))
msg = '{0:>5}%'.format(self.stats['steal'])
msg = '{:>5}%'.format(self.stats['steal'])
ret.append(self.curse_add_line(
msg, self.get_views(key='steal', option='decoration'),
optional=self.get_views(key='steal', option='optional')))
# syscalls
# syscalls: number of system calls since boot. Always set to 0 on Linux. (do not display)
if 'syscalls' in self.stats and not LINUX:
msg = ' {0:8}'.format('syscal:')
msg = ' {:8}'.format('syscal:')
ret.append(self.curse_add_line(msg, optional=self.get_views(key='syscalls', option='optional')))
msg = '{0:>5}'.format(int(self.stats['syscalls'] // self.stats['time_since_update']))
msg = '{:>5}'.format(int(self.stats['syscalls'] // self.stats['time_since_update']))
ret.append(self.curse_add_line(msg, optional=self.get_views(key='syscalls', option='optional')))
# Return the message with decoration
......
......@@ -165,17 +165,17 @@ class Plugin(GlancesPlugin):
# Build the string message
# Header
msg = '{0:9}'.format('DISK I/O')
msg = '{:9}'.format('DISK I/O')
ret.append(self.curse_add_line(msg, "TITLE"))
if args.diskio_iops:
msg = '{0:>7}'.format('IOR/s')
msg = '{:>7}'.format('IOR/s')
ret.append(self.curse_add_line(msg))
msg = '{0:>7}'.format('IOW/s')
msg = '{:>7}'.format('IOW/s')
ret.append(self.curse_add_line(msg))
else:
msg = '{0:>7}'.format('R/s')
msg = '{:>7}'.format('R/s')
ret.append(self.curse_add_line(msg))
msg = '{0:>7}'.format('W/s')
msg = '{:>7}'.format('W/s')
ret.append(self.curse_add_line(msg))
# Disk list (sorted by name)
for i in sorted(self.stats, key=operator.itemgetter(self.get_key())):
......@@ -189,7 +189,7 @@ class Plugin(GlancesPlugin):
if len(disk_name) > 9:
# Cut disk name if it is too long
disk_name = '_' + disk_name[-8:]
msg = '{0:9}'.format(disk_name)
msg = '{:9}'.format(disk_name)
ret.append(self.curse_add_line(msg))
if args.diskio_iops:
# count
......@@ -197,12 +197,12 @@ class Plugin(GlancesPlugin):
int(i['read_count'] // i['time_since_update']))
rxps = self.auto_unit(
int(i['write_count'] // i['time_since_update']))
msg = '{0:>7}'.format(txps)
msg = '{:>7}'.format(txps)
ret.append(self.curse_add_line(msg,
self.get_views(item=i[self.get_key()],
key='read_count',
option='decoration')))
msg = '{0:>7}'.format(rxps)
msg = '{:>7}'.format(rxps)
ret.append(self.curse_add_line(msg,
self.get_views(item=i[self.get_key()],
key='write_count',
......@@ -213,12 +213,12 @@ class Plugin(GlancesPlugin):
int(i['read_bytes'] // i['time_since_update']))
rxps = self.auto_unit(
int(i['write_bytes'] // i['time_since_update']))
msg = '{0:>7}'.format(txps)
msg = '{:>7}'.format(txps)
ret.append(self.curse_add_line(msg,
self.get_views(item=i[self.get_key()],
key='read_bytes',
option='decoration')))
msg = '{0:>7}'.format(rxps)
msg = '{:>7}'.format(rxps)
ret.append(self.curse_add_line(msg,
self.get_views(item=i[self.get_key()],
key='write_bytes',
......
......@@ -86,7 +86,7 @@ class Plugin(GlancesPlugin):
try:
ret = self.stats['containers']
except KeyError as e:
logger.debug("Docker export error {0}".format(e))
logger.debug("Docker export error {}".format(e))
return ret
def connect(self, version=None):
......@@ -175,7 +175,7 @@ class Plugin(GlancesPlugin):
self.stats['version'] = self.docker_client.version()
except Exception as e:
# Correct issue#649
logger.error("{0} plugin - Cannot get Docker version ({1})".format(self.plugin_name, e))
logger.error("{} plugin - Cannot get Docker version ({})".format(self.plugin_name, e))
return self.stats
# Container globals information
......@@ -192,7 +192,7 @@ class Plugin(GlancesPlugin):
try:
self.stats['containers'] = self.docker_client.containers() or []
except Exception as e:
logger.error("{0} plugin - Cannot get containers list ({1})".format(self.plugin_name, e))
logger.error("{} plugin - Cannot get containers list ({})".format(self.plugin_name, e))
return self.stats
# Start new thread for new container
......@@ -200,7 +200,7 @@ class Plugin(GlancesPlugin):
if container['Id'] not in self.thread_list:
# Thread did not exist in the internal dict
# Create it and add it to the internal dict
logger.debug("{0} plugin - Create thread for container {1}".format(self.plugin_name, container['Id'][:12]))
logger.debug("{} plugin - Create thread for container {}".format(self.plugin_name, container['Id'][:12]))
t = ThreadDockerGrabber(self.docker_client, container['Id'])
self.thread_list[container['Id']] = t
t.start()
......@@ -209,7 +209,7 @@ class Plugin(GlancesPlugin):
nonexisting_containers = set(iterkeys(self.thread_list)) - set([c['Id'] for c in self.stats['containers']])
for container_id in nonexisting_containers:
# Stop the thread
logger.debug("{0} plugin - Stop thread for old container {1}".format(self.plugin_name, container_id[:12]))
logger.debug("{} plugin - Stop thread for old container {}".format(self.plugin_name, container_id[:12]))
self.thread_list[container_id].stop()
# Delete the item from the dict
del self.thread_list[container_id]
......@@ -255,7 +255,7 @@ class Plugin(GlancesPlugin):
cpu_new['nb_core'] = len(all_stats['cpu_stats']['cpu_usage']['percpu_usage'] or [])
except KeyError as e:
# all_stats do not have CPU information
logger.debug("Can not grab CPU usage for container {0} ({1})".format(container_id, e))
logger.debug("Cannot grab CPU usage for container {} ({})".format(container_id, e))
logger.debug(all_stats)
else:
# Previous CPU stats stored in the cpu_old variable
......@@ -303,7 +303,7 @@ class Plugin(GlancesPlugin):
ret['max_usage'] = all_stats['memory_stats']['max_usage']
except (KeyError, TypeError) as e:
# all_stats do not have MEM information
logger.debug("Can not grab MEM usage for container {0} ({1})".format(container_id, e))
logger.debug("Cannot grab MEM usage for container {} ({})".format(container_id, e))
logger.debug(all_stats)
# Return the stats
return ret
......@@ -326,7 +326,7 @@ class Plugin(GlancesPlugin):
netcounters = all_stats["networks"]
except KeyError as e:
# all_stats do not have NETWORK information
logger.debug("Can not grab NET usage for container {0} ({1})".format(container_id, e))
logger.debug("Cannot grab NET usage for container {} ({})".format(container_id, e))
logger.debug(all_stats)
# No fallback available...
return network_new
......@@ -350,14 +350,14 @@ class Plugin(GlancesPlugin):
# XML/RPC API, which would otherwise be overly difficult work
# for users of the API
try:
network_new['time_since_update'] = getTimeSinceLastUpdate('docker_net_{0}'.format(container_id))
network_new['time_since_update'] = getTimeSinceLastUpdate('docker_net_{}'.format(container_id))
network_new['rx'] = netcounters["eth0"]["rx_bytes"] - self.netcounters_old[container_id]["eth0"]["rx_bytes"]
network_new['tx'] = netcounters["eth0"]["tx_bytes"] - self.netcounters_old[container_id]["eth0"]["tx_bytes"]
network_new['cumulative_rx'] = netcounters["eth0"]["rx_bytes"]
network_new['cumulative_tx'] = netcounters["eth0"]["tx_bytes"]
except KeyError:
# all_stats do not have INTERFACE information
logger.debug("Can not grab network interface usage for container {0} ({1})".format(container_id, e))
logger.debug("Cannot grab network interface usage for container {} ({})".format(container_id, e))
logger.debug(all_stats)
# Save stats to compute next bitrate
......@@ -384,7 +384,7 @@ class Plugin(GlancesPlugin):
iocounters = all_stats["blkio_stats"]
except KeyError as e:
# all_stats do not have io information
logger.debug("Can not grab block IO usage for container {0} ({1})".format(container_id, e))
logger.debug("Cannot grab block IO usage for container {} ({})".format(container_id, e))
logger.debug(all_stats)
# No fallback available...
return io_new
......@@ -415,9 +415,9 @@ class Plugin(GlancesPlugin):
iow_old = [i for i in self.iocounters_old[container_id]['io_service_bytes_recursive'] if i['op'] == 'Write'][0]['value']
except (IndexError, KeyError) as e:
# all_stats do not have io information
logger.debug("Can not grab block IO usage for container {0} ({1})".format(container_id, e))
logger.debug("Cannot grab block IO usage for container {} ({})".format(container_id, e))
else:
io_new['time_since_update'] = getTimeSinceLastUpdate('docker_io_{0}'.format(container_id))
io_new['time_since_update'] = getTimeSinceLastUpdate('docker_io_{}'.format(container_id))
io_new['ior'] = ior - ior_old
io_new['iow'] = iow - iow_old
io_new['cumulative_ior'] = ior
......@@ -444,45 +444,44 @@ class Plugin(GlancesPlugin):
# Build the string message
# Title
msg = '{0}'.format('CONTAINERS')
msg = '{}'.format('CONTAINERS')
ret.append(self.curse_add_line(msg, "TITLE"))
msg = ' {0}'.format(len(self.stats['containers']))
msg = ' {}'.format(len(self.stats['containers']))
ret.append(self.curse_add_line(msg))
msg = ' ({0} {1})'.format('served by Docker',
self.stats['version']["Version"])
msg = ' (served by Docker {})'.format(self.stats['version']["Version"])
ret.append(self.curse_add_line(msg))
ret.append(self.curse_new_line())
# Header
ret.append(self.curse_new_line())
# msg = '{0:>14}'.format('Id')
# msg = '{:>14}'.format('Id')
# ret.append(self.curse_add_line(msg))
# Get the maximum containers name (cutted to 20 char max)
name_max_width = min(20, len(max(self.stats['containers'], key=lambda x: len(x['name']))['name']))
msg = ' {0:{width}}'.format('Name', width=name_max_width)
msg = ' {:{width}}'.format('Name', width=name_max_width)
ret.append(self.curse_add_line(msg))
msg = '{0:>26}'.format('Status')
msg = '{:>26}'.format('Status')
ret.append(self.curse_add_line(msg))
msg = '{0:>6}'.format('CPU%')
msg = '{:>6}'.format('CPU%')
ret.append(self.curse_add_line(msg))
msg = '{0:>7}'.format('MEM')
msg = '{:>7}'.format('MEM')
ret.append(self.curse_add_line(msg))
msg = '{0:>7}'.format('/MAX')
msg = '{:>7}'.format('/MAX')
ret.append(self.curse_add_line(msg))
msg = '{0:>7}'.format('IOR/s')
msg = '{:>7}'.format('IOR/s')
ret.append(self.curse_add_line(msg))
msg = '{0:>7}'.format('IOW/s')
msg = '{:>7}'.format('IOW/s')
ret.append(self.curse_add_line(msg))
msg = '{0:>7}'.format('Rx/s')
msg = '{:>7}'.format('Rx/s')
ret.append(self.curse_add_line(msg))
msg = '{0:>7}'.format('Tx/s')
msg = '{:>7}'.format('Tx/s')
ret.append(self.curse_add_line(msg))
msg = ' {0:8}'.format('Command')
msg = ' {:8}'.format('Command')
ret.append(self.curse_add_line(msg))
# Data
for container in self.stats['containers']:
ret.append(self.curse_new_line())
# Id
# msg = '{0:>14}'.format(container['Id'][0:12])
# msg = '{:>14}'.format(container['Id'][0:12])
# ret.append(self.curse_add_line(msg))
# Name
name = container['name']
......@@ -490,37 +489,37 @@ class Plugin(GlancesPlugin):
name = '_' + name[-name_max_width + 1:]
else:
name = name[:name_max_width]
msg = ' {0:{width}}'.format(name, width=name_max_width)
msg = ' {:{width}}'.format(name, width=name_max_width)
ret.append(self.curse_add_line(msg))
# Status
status = self.container_alert(container['Status'])
msg = container['Status'].replace("minute", "min")
msg = '{0:>26}'.format(msg[0:25])
msg = '{:>26}'.format(msg[0:25])
ret.append(self.curse_add_line(msg, status))
# CPU
try:
msg = '{0:>6.1f}'.format(container['cpu']['total'])
msg = '{:>6.1f}'.format(container['cpu']['total'])
except KeyError:
msg = '{0:>6}'.format('?')
msg = '{:>6}'.format('?')
ret.append(self.curse_add_line(msg))
# MEM
try:
msg = '{0:>7}'.format(self.auto_unit(container['memory']['usage']))
msg = '{:>7}'.format(self.auto_unit(container['memory']['usage']))
except KeyError:
msg = '{0:>7}'.format('?')
msg = '{:>7}'.format('?')
ret.append(self.curse_add_line(msg))
try:
msg = '{0:>7}'.format(self.auto_unit(container['memory']['limit']))
msg = '{:>7}'.format(self.auto_unit(container['memory']['limit']))
except KeyError:
msg = '{0:>7}'.format('?')
msg = '{:>7}'.format('?')
ret.append(self.curse_add_line(msg))
# IO R/W
for r in ['ior', 'iow']:
try:
value = self.auto_unit(int(container['io'][r] // container['io']['time_since_update'] * 8)) + "b"
msg = '{0:>7}'.format(value)
msg = '{:>7}'.format(value)
except KeyError:
msg = '{0:>7}'.format('?')
msg = '{:>7}'.format('?')
ret.append(self.curse_add_line(msg))
# NET RX/TX
if args.byte:
......@@ -534,12 +533,12 @@ class Plugin(GlancesPlugin):
for r in ['rx', 'tx']:
try:
value = self.auto_unit(int(container['network'][r] // container['network']['time_since_update'] * to_bit)) + unit
msg = '{0:>7}'.format(value)
msg = '{:>7}'.format(value)
except KeyError:
msg = '{0:>7}'.format('?')
msg = '{:>7}'.format('?')
ret.append(self.curse_add_line(msg))
# Command
msg = ' {0}'.format(container['Command'])
msg = ' {}'.format(container['Command'])
ret.append(self.curse_add_line(msg, splittable=True))
return ret
......@@ -563,7 +562,7 @@ class ThreadDockerGrabber(threading.Thread):
"""Init the class:
docker_client: instance of Docker-py client
container_id: Id of the container"""
logger.debug("docker plugin - Create thread for container {0}".format(container_id[:12]))
logger.debug("docker plugin - Create thread for container {}".format(container_id[:12]))
super(ThreadDockerGrabber, self).__init__()
# Event needed to stop properly the thread
self._stopper = threading.Event()
......@@ -595,7 +594,7 @@ class ThreadDockerGrabber(threading.Thread):
def stop(self, timeout=None):
"""Stop the thread"""
logger.debug("docker plugin - Close thread for container {0}".format(self._container_id[:12]))
logger.debug("docker plugin - Close thread for container {}".format(self._container_id[:12]))
self._stopper.set()
def stopped(self):
......
......@@ -101,7 +101,7 @@ class Plugin(GlancesPlugin):
# Build the string message
# Header
msg = '{0}'.format('FOLDERS')
msg = '{}'.format('FOLDERS')
ret.append(self.curse_add_line(msg, "TITLE"))
# Data
......@@ -112,12 +112,12 @@ class Plugin(GlancesPlugin):
path = '_' + i['path'][-15 + 1:]
else:
path = i['path']
msg = '{0:<16} '.format(path)
msg = '{:<16} '.format(path)
ret.append(self.curse_add_line(msg))
try:
msg = '{0:>6}'.format(self.auto_unit(i['size']))
msg = '{:>6}'.format(self.auto_unit(i['size']))
except (TypeError, ValueError):
msg = '{0:>6}'.format(i['size'])
msg = '{:>6}'.format(i['size'])
ret.append(self.curse_add_line(msg, self.get_alert(i)))
return ret
......@@ -214,14 +214,14 @@ class Plugin(GlancesPlugin):
# Build the string message
# Header
msg = '{0:{width}}'.format('FILE SYS', width=fsname_max_width)
msg = '{:{width}}'.format('FILE SYS', width=fsname_max_width)
ret.append(self.curse_add_line(msg, "TITLE"))
if args.fs_free_space:
msg = '{0:>7}'.format('Free')
msg = '{:>7}'.format('Free')
else:
msg = '{0:>7}'.format('Used')
msg = '{:>7}'.format('Used')
ret.append(self.curse_add_line(msg))
msg = '{0:>7}'.format('Total')
msg = '{:>7}'.format('Total')
ret.append(self.curse_add_line(msg))
# Filesystem list (sorted by name)
......@@ -239,16 +239,16 @@ class Plugin(GlancesPlugin):
mnt_point = '_' + i['mnt_point'][-fsname_max_width + 1:]
else:
mnt_point = i['mnt_point']
msg = '{0:{width}}'.format(mnt_point, width=fsname_max_width)
msg = '{:{width}}'.format(mnt_point, width=fsname_max_width)
ret.append(self.curse_add_line(msg))
if args.fs_free_space:
msg = '{0:>7}'.format(self.auto_unit(i['free']))
msg = '{:>7}'.format(self.auto_unit(i['free']))
else:
msg = '{0:>7}'.format(self.auto_unit(i['used']))
msg = '{:>7}'.format(self.auto_unit(i['used']))
ret.append(self.curse_add_line(msg, self.get_views(item=i[self.get_key()],
key='used',
option='decoration')))
msg = '{0:>7}'.format(self.auto_unit(i['size']))
msg = '{:>7}'.format(self.auto_unit(i['size']))
ret.append(self.curse_add_line(msg))
return ret
......@@ -143,7 +143,7 @@ class GlancesGrabHDDTemp(object):
sck.connect((self.host, self.port))
data = sck.recv(4096)
except socket.error as e:
logger.debug("Can not connect to an HDDtemp server ({0}:{1} => {2})".format(self.host, self.port, e))
logger.debug("Cannot connect to an HDDtemp server ({}:{} => {})".format(self.host, self.port, e))
logger.debug("Disable the HDDtemp module. Use the --disable-hddtemp to hide the previous message.")
self.args.disable_hddtemp = True
data = ""
......
......@@ -50,16 +50,16 @@ class Plugin(GlancesPlugin):
pass
def generate_view_data(self):
self.view_data['version'] = '{0} {1}'.format(__appname__.title(), __version__)
self.view_data['psutil_version'] = ' with PSutil {0}'.format(psutil_version)
self.view_data['version'] = '{} {}'.format(__appname__.title(), __version__)
self.view_data['psutil_version'] = ' with PSutil {}'.format(psutil_version)
try:
self.view_data['configuration_file'] = 'Configuration file: {0}'.format(self.config.loaded_config_file)
self.view_data['configuration_file'] = 'Configuration file: {}'.format(self.config.loaded_config_file)
except AttributeError:
pass
msg_col = ' {0:1} {1:35}'
msg_col2 = ' {0:1} {1:35}'
msg_col = ' {:1} {:35}'
msg_col2 = ' {:1} {:35}'
self.view_data['sort_auto'] = msg_col.format('a', 'Sort processes automatically')
self.view_data['sort_network'] = msg_col2.format('b', 'Bytes or bits for network I/O')
self.view_data['sort_cpu'] = msg_col.format('c', 'Sort processes by CPU%')
......
......@@ -88,7 +88,7 @@ class Plugin(GlancesPlugin):
try:
default_gw = netifaces.gateways()['default'][netifaces.AF_INET]
except (KeyError, AttributeError) as e:
logger.debug("Cannot grab the default gateway ({0})".format(e))
logger.debug("Cannot grab the default gateway ({})".format(e))
else:
try:
self.stats['address'] = netifaces.ifaddresses(default_gw[1])[netifaces.AF_INET][0]['addr']
......@@ -98,7 +98,7 @@ class Plugin(GlancesPlugin):
# !!! SHOULD be done once, not on each refresh
self.stats['public_address'] = self.public_address
except (KeyError, AttributeError) as e:
logger.debug("Cannot grab IP information: {0}".format(e))
logger.debug("Cannot grab IP information: {}".format(e))
elif self.input_method == 'snmp':
# Not implemented yet
pass
......@@ -132,14 +132,14 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg))
msg = 'IP '
ret.append(self.curse_add_line(msg, 'TITLE'))
msg = '{0:}'.format(self.stats['address'])
msg = '{}'.format(self.stats['address'])
ret.append(self.curse_add_line(msg))
if 'mask_cidr' in self.stats:
# VPN with no internet access (issue #842)
msg = '/{0}'.format(self.stats['mask_cidr'])
msg = '/{}'.format(self.stats['mask_cidr'])
ret.append(self.curse_add_line(msg))
try:
msg_pub = '{0:}'.format(self.stats['public_address'])
msg_pub = '{}'.format(self.stats['public_address'])
except UnicodeEncodeError:
pass
else:
......
......@@ -136,33 +136,33 @@ class Plugin(GlancesPlugin):
# Build the string message
# Header
msg = '{0:8}'.format('LOAD')
msg = '{:8}'.format('LOAD')
ret.append(self.curse_add_line(msg, "TITLE"))
# Core number
if 'cpucore' in self.stats and self.stats['cpucore'] > 0:
msg = '{0}-core'.format(int(self.stats['cpucore']))
msg = '{}-core'.format(int(self.stats['cpucore']))
ret.append(self.curse_add_line(msg))
# New line
ret.append(self.curse_new_line())
# 1min load
msg = '{0:8}'.format('1 min:')
msg = '{:8}'.format('1 min:')
ret.append(self.curse_add_line(msg))
msg = '{0:>6.2f}'.format(self.stats['min1'])
msg = '{:>6.2f}'.format(self.stats['min1'])
ret.append(self.curse_add_line(msg))
# New line
ret.append(self.curse_new_line())
# 5min load
msg = '{0:8}'.format('5 min:')
msg = '{:8}'.format('5 min:')
ret.append(self.curse_add_line(msg))
msg = '{0:>6.2f}'.format(self.stats['min5'])
msg = '{:>6.2f}'.format(self.stats['min5'])
ret.append(self.curse_add_line(
msg, self.get_views(key='min5', option='decoration')))
# New line
ret.append(self.curse_new_line())
# 15min load
msg = '{0:8}'.format('15 min:')
msg = '{:8}'.format('15 min:')
ret.append(self.curse_add_line(msg))
msg = '{0:>6.2f}'.format(self.stats['min15'])
msg = '{:>6.2f}'.format(self.stats['min15'])
ret.append(self.curse_add_line(
msg, self.get_views(key='min15', option='decoration')))
......
......@@ -185,56 +185,56 @@ class Plugin(GlancesPlugin):
# Build the string message
# Header
msg = '{0:5} '.format('MEM')
msg = '{:5} '.format('MEM')
ret.append(self.curse_add_line(msg, "TITLE"))
# Percent memory usage
msg = '{0:>7.1%}'.format(self.stats['percent'] / 100)
msg = '{:>7.1%}'.format(self.stats['percent'] / 100)
ret.append(self.curse_add_line(msg))
# Active memory usage
if 'active' in self.stats:
msg = ' {0:9}'.format('active:')
msg = ' {:9}'.format('active:')
ret.append(self.curse_add_line(msg, optional=self.get_views(key='active', option='optional')))
msg = '{0:>7}'.format(self.auto_unit(self.stats['active']))
msg = '{:>7}'.format(self.auto_unit(self.stats['active']))
ret.append(self.curse_add_line(msg, optional=self.get_views(key='active', option='optional')))
# New line
ret.append(self.curse_new_line())
# Total memory usage
msg = '{0:6}'.format('total:')
msg = '{:6}'.format('total:')
ret.append(self.curse_add_line(msg))
msg = '{0:>7}'.format(self.auto_unit(self.stats['total']))
msg = '{:>7}'.format(self.auto_unit(self.stats['total']))
ret.append(self.curse_add_line(msg))
# Inactive memory usage
if 'inactive' in self.stats:
msg = ' {0:9}'.format('inactive:')
msg = ' {:9}'.format('inactive:')
ret.append(self.curse_add_line(msg, optional=self.get_views(key='inactive', option='optional')))
msg = '{0:>7}'.format(self.auto_unit(self.stats['inactive']))
msg = '{:>7}'.format(self.auto_unit(self.stats['inactive']))
ret.append(self.curse_add_line(msg, optional=self.get_views(key='inactive', option='optional')))
# New line
ret.append(self.curse_new_line())
# Used memory usage
msg = '{0:6}'.format('used:')
msg = '{:6}'.format('used:')
ret.append(self.curse_add_line(msg))
msg = '{0:>7}'.format(self.auto_unit(self.stats['used']))
msg = '{:>7}'.format(self.auto_unit(self.stats['used']))
ret.append(self.curse_add_line(
msg, self.get_views(key='used', option='decoration')))
# Buffers memory usage
if 'buffers' in self.stats:
msg = ' {0:9}'.format('buffers:')
msg = ' {:9}'.format('buffers:')
ret.append(self.curse_add_line(msg, optional=self.get_views(key='buffers', option='optional')))
msg = '{0:>7}'.format(self.auto_unit(self.stats['buffers']))
msg = '{:>7}'.format(self.auto_unit(self.stats['buffers']))
ret.append(self.curse_add_line(msg, optional=self.get_views(key='buffers', option='optional')))
# New line
ret.append(self.curse_new_line())
# Free memory usage
msg = '{0:6}'.format('free:')
msg = '{:6}'.format('free:')
ret.append(self.curse_add_line(msg))
msg = '{0:>7}'.format(self.auto_unit(self.stats['free']))
msg = '{:>7}'.format(self.auto_unit(self.stats['free']))
ret.append(self.curse_add_line(msg))
# Cached memory usage
if 'cached' in self.stats:
msg = ' {0:9}'.format('cached:')
msg = ' {:9}'.format('cached:')
ret.append(self.curse_add_line(msg, optional=self.get_views(key='cached', option='optional')))
msg = '{0:>7}'.format(self.auto_unit(self.stats['cached']))
msg = '{:>7}'.format(self.auto_unit(self.stats['cached']))
ret.append(self.curse_add_line(msg, optional=self.get_views(key='cached', option='optional')))
return ret
......@@ -156,32 +156,32 @@ class Plugin(GlancesPlugin):
# Build the string message
# Header
msg = '{0:7} '.format('SWAP')
msg = '{:7} '.format('SWAP')
ret.append(self.curse_add_line(msg, "TITLE"))
# Percent memory usage
msg = '{0:>6.1%}'.format(self.stats['percent'] / 100)
msg = '{:>6.1%}'.format(self.stats['percent'] / 100)
ret.append(self.curse_add_line(msg))
# New line
ret.append(self.curse_new_line())
# Total memory usage
msg = '{0:8}'.format('total:')
msg = '{:8}'.format('total:')
ret.append(self.curse_add_line(msg))
msg = '{0:>6}'.format(self.auto_unit(self.stats['total']))
msg = '{:>6}'.format(self.auto_unit(self.stats['total']))
ret.append(self.curse_add_line(msg))
# New line
ret.append(self.curse_new_line())
# Used memory usage
msg = '{0:8}'.format('used:')
msg = '{:8}'.format('used:')
ret.append(self.curse_add_line(msg))
msg = '{0:>6}'.format(self.auto_unit(self.stats['used']))
msg = '{:>6}'.format(self.auto_unit(self.stats['used']))
ret.append(self.curse_add_line(
msg, self.get_views(key='used', option='decoration')))
# New line
ret.append(self.curse_new_line())
# Free memory usage
msg = '{0:8}'.format('free:')
msg = '{:8}'.format('free:')
ret.append(self.curse_add_line(msg))
msg = '{0:>6}'.format(self.auto_unit(self.stats['free']))
msg = '{:>6}'.format(self.auto_unit(self.stats['free']))
ret.append(self.curse_add_line(msg))
return ret
......@@ -246,30 +246,30 @@ class Plugin(GlancesPlugin):
# Build the string message
# Header
msg = '{0:{width}}'.format('NETWORK', width=ifname_max_width)
msg = '{:{width}}'.format('NETWORK', width=ifname_max_width)
ret.append(self.curse_add_line(msg, "TITLE"))
if args.network_cumul:
# Cumulative stats
if args.network_sum:
# Sum stats
msg = '{0:>14}'.format('Rx+Tx')
msg = '{:>14}'.format('Rx+Tx')
ret.append(self.curse_add_line(msg))
else:
# Rx/Tx stats
msg = '{0:>7}'.format('Rx')
msg = '{:>7}'.format('Rx')
ret.append(self.curse_add_line(msg))
msg = '{0:>7}'.format('Tx')
msg = '{:>7}'.format('Tx')
ret.append(self.curse_add_line(msg))
else:
# Bitrate stats
if args.network_sum:
# Sum stats
msg = '{0:>14}'.format('Rx+Tx/s')
msg = '{:>14}'.format('Rx+Tx/s')
ret.append(self.curse_add_line(msg))
else:
msg = '{0:>7}'.format('Rx/s')
msg = '{:>7}'.format('Rx/s')
ret.append(self.curse_add_line(msg))
msg = '{0:>7}'.format('Tx/s')
msg = '{:>7}'.format('Tx/s')
ret.append(self.curse_add_line(msg))
# Interface list (sorted by name)
for i in sorted(self.stats, key=operator.itemgetter(self.get_key())):
......@@ -308,16 +308,16 @@ class Plugin(GlancesPlugin):
# New line
ret.append(self.curse_new_line())
msg = '{0:{width}}'.format(ifname, width=ifname_max_width)
msg = '{:{width}}'.format(ifname, width=ifname_max_width)
ret.append(self.curse_add_line(msg))
if args.network_sum:
msg = '{0:>14}'.format(sx)
msg = '{:>14}'.format(sx)
ret.append(self.curse_add_line(msg))
else:
msg = '{0:>7}'.format(rx)
msg = '{:>7}'.format(rx)
ret.append(self.curse_add_line(
msg, self.get_views(item=i[self.get_key()], key='rx', option='decoration')))
msg = '{0:>7}'.format(tx)
msg = '{:>7}'.format(tx)
ret.append(self.curse_add_line(
msg, self.get_views(item=i[self.get_key()], key='tx', option='decoration')))
......
......@@ -53,7 +53,7 @@ class Plugin(GlancesPlugin):
# Build the string message
# 23 is the padding for the process list
msg = '{0:23}'.format(self.stats)
msg = '{:23}'.format(self.stats)
ret.append(self.curse_add_line(msg))
return ret
......@@ -81,12 +81,12 @@ class Plugin(GlancesPlugin):
# Build the string message
# Header
msg = '{0:8}'.format('PER CPU')
msg = '{:8}'.format('PER CPU')
ret.append(self.curse_add_line(msg, "TITLE"))
# Total per-CPU usage
for cpu in self.stats:
msg = '{0:>6}%'.format(cpu['total'])
msg = '{:>6}%'.format(cpu['total'])
ret.append(self.curse_add_line(msg))
# Stats per-CPU
......@@ -95,10 +95,10 @@ class Plugin(GlancesPlugin):
continue
ret.append(self.curse_new_line())
msg = '{0:8}'.format(stat + ':')
msg = '{:8}'.format(stat + ':')
ret.append(self.curse_add_line(msg))
for cpu in self.stats:
msg = '{0:>6}%'.format(cpu[stat])
msg = '{:>6}%'.format(cpu[stat])
ret.append(self.curse_add_line(msg,
self.get_alert(cpu[stat], header=stat)))
......
......@@ -72,7 +72,7 @@ class GlancesPlugin(object):
def exit(self):
"""Method to be called when Glances exit"""
logger.debug("Stop the {0} plugin".format(self.plugin_name))
logger.debug("Stop the {} plugin".format(self.plugin_name))
def __repr__(self):
"""Return the raw stats."""
......@@ -98,7 +98,7 @@ class GlancesPlugin(object):
ret = None
if self.args is not None and self.args.enable_history and self.get_items_history_list() is not None:
init_list = [i['name'] for i in self.get_items_history_list()]
logger.debug("Stats history activated for plugin {0} (items: {1})".format(self.plugin_name, init_list))
logger.debug("Stats history activated for plugin {} (items: {})".format(self.plugin_name, init_list))
ret = {}
return ret
......@@ -106,7 +106,7 @@ class GlancesPlugin(object):
"""Reset the stats history (dict of list)."""
if self.args is not None and self.args.enable_history and self.get_items_history_list() is not None:
reset_list = [i['name'] for i in self.get_items_history_list()]
logger.debug("Reset history for plugin {0} (items: {1})".format(self.plugin_name, reset_list))
logger.debug("Reset history for plugin {} (items: {})".format(self.plugin_name, reset_list))
self.stats_history = {}
def update_stats_history(self, item_name=''):
......@@ -241,7 +241,7 @@ class GlancesPlugin(object):
try:
return json.dumps({item: self.stats[item]})
except KeyError as e:
logger.error("Cannot get item {0} ({1})".format(item, e))
logger.error("Cannot get item {} ({})".format(item, e))
return None
elif isinstance(self.stats, list):
try:
......@@ -249,7 +249,7 @@ class GlancesPlugin(object):
# http://stackoverflow.com/questions/4573875/python-get-index-of-dictionary-item-in-list
return json.dumps({item: map(itemgetter(item), self.stats)})
except (KeyError, ValueError) as e:
logger.error("Cannot get item {0} ({1})".format(item, e))
logger.error("Cannot get item {} ({})".format(item, e))
return None
else:
return None
......@@ -268,7 +268,7 @@ class GlancesPlugin(object):
return json.dumps({value: [i for i in self.stats if i[item] == value]})
except (KeyError, ValueError) as e:
logger.error(
"Cannot get item({0})=value({1}) ({2})".format(item, value, e))
"Cannot get item({})=value({}) ({})".format(item, value, e))
return None
def update_views(self):
......@@ -346,7 +346,7 @@ class GlancesPlugin(object):
self._limits[limit] = config.get_float_value(self.plugin_name, level)
except ValueError:
self._limits[limit] = config.get_value(self.plugin_name, level).split(",")
logger.debug("Load limit: {0} = {1}".format(limit, self._limits[limit]))
logger.debug("Load limit: {} = {}".format(limit, self._limits[limit]))
@property
def limits(self):
......@@ -455,7 +455,7 @@ class GlancesPlugin(object):
# Exemple: network_careful
limit = self._limits[self.plugin_name + '_' + criticity]
# logger.debug("{0} {1} value is {2}".format(stat_name, criticity, limit))
# logger.debug("{} {} value is {}".format(stat_name, criticity, limit))
# Return the limit
return limit
......@@ -650,9 +650,9 @@ class GlancesPlugin(object):
decimal_precision = min(1, decimal_precision)
elif symbol in 'K':
decimal_precision = 0
return '{0:.{decimal}f}{symbol}'.format(
return '{:.{decimal}f}{symbol}'.format(
value, decimal=decimal_precision, symbol=symbol)
return '{0!s}'.format(number)
return '{!s}'.format(number)
def _log_result_decorator(fct):
"""Log (DEBUG) the result of the function fct."""
......
......@@ -83,9 +83,9 @@ class Plugin(GlancesPlugin):
if glances_processes.process_filter is not None:
msg = 'Processes filter:'
ret.append(self.curse_add_line(msg, "TITLE"))
msg = ' {0} '.format(glances_processes.process_filter)
msg = ' {} '.format(glances_processes.process_filter)
if glances_processes.process_filter_key is not None:
msg += 'on column {0} '.format(glances_processes.process_filter_key)
msg += 'on column {} '.format(glances_processes.process_filter_key)
ret.append(self.curse_add_line(msg, "FILTER"))
msg = '(\'ENTER\' to edit, \'E\' to reset)'
ret.append(self.curse_add_line(msg))
......@@ -97,34 +97,34 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg, "TITLE"))
# Compute processes
other = self.stats['total']
msg = '{0:>4}'.format(self.stats['total'])
msg = '{:>4}'.format(self.stats['total'])
ret.append(self.curse_add_line(msg))
if 'thread' in self.stats:
msg = ' ({0} thr),'.format(self.stats['thread'])
msg = ' ({} thr),'.format(self.stats['thread'])
ret.append(self.curse_add_line(msg))
if 'running' in self.stats:
other -= self.stats['running']
msg = ' {0} run,'.format(self.stats['running'])
msg = ' {} run,'.format(self.stats['running'])
ret.append(self.curse_add_line(msg))
if 'sleeping' in self.stats:
other -= self.stats['sleeping']
msg = ' {0} slp,'.format(self.stats['sleeping'])
msg = ' {} slp,'.format(self.stats['sleeping'])
ret.append(self.curse_add_line(msg))
msg = ' {0} oth '.format(other)
msg = ' {} oth '.format(other)
ret.append(self.curse_add_line(msg))
# Display sort information
if glances_processes.auto_sort:
msg = 'sorted automatically'
ret.append(self.curse_add_line(msg))
msg = ' by {0}'.format(glances_processes.sort_key)
msg = ' by {}'.format(glances_processes.sort_key)
ret.append(self.curse_add_line(msg))
else:
msg = 'sorted by {0}'.format(glances_processes.sort_key)
msg = 'sorted by {}'.format(glances_processes.sort_key)
ret.append(self.curse_add_line(msg))
ret[-1]["msg"] += ", %s view" % ("tree" if glances_processes.is_tree_enabled() else "flat")
# if args.disable_irix:
......
......@@ -195,69 +195,69 @@ class Plugin(GlancesPlugin):
# CPU
if 'cpu_percent' in p and p['cpu_percent'] is not None and p['cpu_percent'] != '':
if args.disable_irix and self.nb_log_core != 0:
msg = '{0:>6.1f}'.format(p['cpu_percent'] / float(self.nb_log_core))
msg = '{:>6.1f}'.format(p['cpu_percent'] / float(self.nb_log_core))
else:
msg = '{0:>6.1f}'.format(p['cpu_percent'])
msg = '{:>6.1f}'.format(p['cpu_percent'])
ret.append(self.curse_add_line(msg,
self.get_alert(p['cpu_percent'], header="cpu")))
else:
msg = '{0:>6}'.format('?')
msg = '{:>6}'.format('?')
ret.append(self.curse_add_line(msg))
# MEM
if 'memory_percent' in p and p['memory_percent'] is not None and p['memory_percent'] != '':
msg = '{0:>6.1f}'.format(p['memory_percent'])
msg = '{:>6.1f}'.format(p['memory_percent'])
ret.append(self.curse_add_line(msg,
self.get_alert(p['memory_percent'], header="mem")))
else:
msg = '{0:>6}'.format('?')
msg = '{:>6}'.format('?')
ret.append(self.curse_add_line(msg))
# VMS/RSS
if 'memory_info' in p and p['memory_info'] is not None and p['memory_info'] != '':
# VMS
msg = '{0:>6}'.format(self.auto_unit(p['memory_info'][1], low_precision=False))
msg = '{:>6}'.format(self.auto_unit(p['memory_info'][1], low_precision=False))
ret.append(self.curse_add_line(msg, optional=True))
# RSS
msg = '{0:>6}'.format(self.auto_unit(p['memory_info'][0], low_precision=False))
msg = '{:>6}'.format(self.auto_unit(p['memory_info'][0], low_precision=False))
ret.append(self.curse_add_line(msg, optional=True))
else:
msg = '{0:>6}'.format('?')
msg = '{:>6}'.format('?')
ret.append(self.curse_add_line(msg))
ret.append(self.curse_add_line(msg))
# PID
msg = '{0:>6}'.format(p['pid'])
msg = '{:>6}'.format(p['pid'])
ret.append(self.curse_add_line(msg))
# USER
if 'username' in p:
# docker internal users are displayed as ints only, therefore str()
msg = ' {0:9}'.format(str(p['username'])[:9])
msg = ' {:9}'.format(str(p['username'])[:9])
ret.append(self.curse_add_line(msg))
else:
msg = ' {0:9}'.format('?')
msg = ' {:9}'.format('?')
ret.append(self.curse_add_line(msg))
# NICE
if 'nice' in p:
nice = p['nice']
if nice is None:
nice = '?'
msg = '{0:>5}'.format(nice)
msg = '{:>5}'.format(nice)
if isinstance(nice, int) and ((WINDOWS and nice != 32) or
(not WINDOWS and nice != 0)):
ret.append(self.curse_add_line(msg, decoration='NICE'))
else:
ret.append(self.curse_add_line(msg))
else:
msg = '{0:>5}'.format('?')
msg = '{:>5}'.format('?')
ret.append(self.curse_add_line(msg))
# STATUS
if 'status' in p:
status = p['status']
msg = '{0:>2}'.format(status)
msg = '{:>2}'.format(status)
if status == 'R':
ret.append(self.curse_add_line(msg, decoration='STATUS'))
else:
ret.append(self.curse_add_line(msg))
else:
msg = '{0:>2}'.format('?')
msg = '{:>2}'.format('?')
ret.append(self.curse_add_line(msg))
# TIME+
if self.tag_proc_time:
......@@ -268,37 +268,37 @@ class Plugin(GlancesPlugin):
# See https://github.com/nicolargo/glances/issues/87
# Also catch TypeError on Mac OS X
# See: https://github.com/nicolargo/glances/issues/622
logger.debug("Cannot get TIME+ ({0})".format(e))
logger.debug("Cannot get TIME+ ({})".format(e))
self.tag_proc_time = False
else:
hours, minutes, seconds, microseconds = convert_timedelta(delta)
if hours:
msg = '{0:>4}h'.format(hours)
msg = '{:>4}h'.format(hours)
ret.append(self.curse_add_line(msg, decoration='CPU_TIME', optional=True))
msg = '{0}:{1}'.format(str(minutes).zfill(2), seconds)
msg = '{}:{}'.format(str(minutes).zfill(2), seconds)
else:
msg = '{0:>4}:{1}.{2}'.format(minutes, seconds, microseconds)
msg = '{:>4}:{}.{}'.format(minutes, seconds, microseconds)
else:
msg = '{0:>10}'.format('?')
msg = '{:>10}'.format('?')
ret.append(self.curse_add_line(msg, optional=True))
# IO read/write
if 'io_counters' in p:
# IO read
io_rs = int((p['io_counters'][0] - p['io_counters'][2]) / p['time_since_update'])
if io_rs == 0:
msg = '{0:>6}'.format("0")
msg = '{:>6}'.format("0")
else:
msg = '{0:>6}'.format(self.auto_unit(io_rs, low_precision=True))
msg = '{:>6}'.format(self.auto_unit(io_rs, low_precision=True))
ret.append(self.curse_add_line(msg, optional=True, additional=True))
# IO write
io_ws = int((p['io_counters'][1] - p['io_counters'][3]) / p['time_since_update'])
if io_ws == 0:
msg = '{0:>6}'.format("0")
msg = '{:>6}'.format("0")
else:
msg = '{0:>6}'.format(self.auto_unit(io_ws, low_precision=True))
msg = '{:>6}'.format(self.auto_unit(io_ws, low_precision=True))
ret.append(self.curse_add_line(msg, optional=True, additional=True))
else:
msg = '{0:>6}'.format("?")
msg = '{:>6}'.format("?")
ret.append(self.curse_add_line(msg, optional=True, additional=True))
ret.append(self.curse_add_line(msg, optional=True, additional=True))
......@@ -311,23 +311,23 @@ class Plugin(GlancesPlugin):
if cmdline and cmdline != ['']:
path, cmd, arguments = split_cmdline(cmdline)
if os.path.isdir(path) and not args.process_short_name:
msg = ' {0}'.format(path) + os.sep
msg = ' {}'.format(path) + os.sep
ret.append(self.curse_add_line(msg, splittable=True))
if glances_processes.is_tree_enabled():
# mark position to add tree decoration
ret[-1]["_tree_decoration"] = True
ret.append(self.curse_add_line(cmd, decoration='PROCESS', splittable=True))
else:
msg = ' {0}'.format(cmd)
msg = ' {}'.format(cmd)
ret.append(self.curse_add_line(msg, decoration='PROCESS', splittable=True))
if glances_processes.is_tree_enabled():
# mark position to add tree decoration
ret[-1]["_tree_decoration"] = True
if arguments:
msg = ' {0}'.format(arguments)
msg = ' {}'.format(arguments)
ret.append(self.curse_add_line(msg, splittable=True))
else:
msg = ' {0}'.format(p['name'])
msg = ' {}'.format(p['name'])
ret.append(self.curse_add_line(msg, splittable=True))
except UnicodeEncodeError:
ret.append(self.curse_add_line('', splittable=True))
......@@ -451,33 +451,33 @@ class Plugin(GlancesPlugin):
sort_style = 'SORT'
if args.disable_irix and 0 < self.nb_log_core < 10:
msg = '{0:>6}'.format('CPU%/' + str(self.nb_log_core))
msg = '{:>6}'.format('CPU%/' + str(self.nb_log_core))
elif args.disable_irix and self.nb_log_core != 0:
msg = '{0:>6}'.format('CPU%/C')
msg = '{:>6}'.format('CPU%/C')
else:
msg = '{0:>6}'.format('CPU%')
msg = '{:>6}'.format('CPU%')
ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'cpu_percent' else 'DEFAULT'))
msg = '{0:>6}'.format('MEM%')
msg = '{:>6}'.format('MEM%')
ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'memory_percent' else 'DEFAULT'))
msg = '{0:>6}'.format('VIRT')
msg = '{:>6}'.format('VIRT')
ret.append(self.curse_add_line(msg, optional=True))
msg = '{0:>6}'.format('RES')
msg = '{:>6}'.format('RES')
ret.append(self.curse_add_line(msg, optional=True))
msg = '{0:>6}'.format('PID')
msg = '{:>6}'.format('PID')
ret.append(self.curse_add_line(msg))
msg = ' {0:10}'.format('USER')
msg = ' {:10}'.format('USER')
ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'username' else 'DEFAULT'))
msg = '{0:>4}'.format('NI')
msg = '{:>4}'.format('NI')
ret.append(self.curse_add_line(msg))
msg = '{0:>2}'.format('S')
msg = '{:>2}'.format('S')
ret.append(self.curse_add_line(msg))
msg = '{0:>10}'.format('TIME+')
msg = '{:>10}'.format('TIME+')
ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'cpu_times' else 'DEFAULT', optional=True))
msg = '{0:>6}'.format('R/s')
msg = '{:>6}'.format('R/s')
ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'io_counters' else 'DEFAULT', optional=True, additional=True))
msg = '{0:>6}'.format('W/s')
msg = '{:>6}'.format('W/s')
ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'io_counters' else 'DEFAULT', optional=True, additional=True))
msg = ' {0:8}'.format('Command')
msg = ' {:8}'.format('Command')
ret.append(self.curse_add_line(msg, sort_style if process_sort_key == 'name' else 'DEFAULT'))
def __msg_curse_sum(self, ret, sep_char='_', mmm=None, args=None):
......@@ -493,73 +493,73 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(sep_char * 69))
ret.append(self.curse_new_line())
# CPU percent sum
msg = '{0:>6.1f}'.format(self.__sum_stats('cpu_percent', mmm=mmm))
msg = '{:>6.1f}'.format(self.__sum_stats('cpu_percent', mmm=mmm))
ret.append(self.curse_add_line(msg,
decoration=self.__mmm_deco(mmm)))
# MEM percent sum
msg = '{0:>6.1f}'.format(self.__sum_stats('memory_percent', mmm=mmm))
msg = '{:>6.1f}'.format(self.__sum_stats('memory_percent', mmm=mmm))
ret.append(self.curse_add_line(msg,
decoration=self.__mmm_deco(mmm)))
# VIRT and RES memory sum
if 'memory_info' in self.stats[0] and self.stats[0]['memory_info'] is not None and self.stats[0]['memory_info'] != '':
# VMS
msg = '{0:>6}'.format(self.auto_unit(self.__sum_stats('memory_info', indice=1, mmm=mmm), low_precision=False))
msg = '{:>6}'.format(self.auto_unit(self.__sum_stats('memory_info', indice=1, mmm=mmm), low_precision=False))
ret.append(self.curse_add_line(msg,
decoration=self.__mmm_deco(mmm),
optional=True))
# RSS
msg = '{0:>6}'.format(self.auto_unit(self.__sum_stats('memory_info', indice=0, mmm=mmm), low_precision=False))
msg = '{:>6}'.format(self.auto_unit(self.__sum_stats('memory_info', indice=0, mmm=mmm), low_precision=False))
ret.append(self.curse_add_line(msg,
decoration=self.__mmm_deco(mmm),
optional=True))
else:
msg = '{0:>6}'.format('')
msg = '{:>6}'.format('')
ret.append(self.curse_add_line(msg))
ret.append(self.curse_add_line(msg))
# PID
msg = '{0:>6}'.format('')
msg = '{:>6}'.format('')
ret.append(self.curse_add_line(msg))
# USER
msg = ' {0:9}'.format('')
msg = ' {:9}'.format('')
ret.append(self.curse_add_line(msg))
# NICE
msg = '{0:>5}'.format('')
msg = '{:>5}'.format('')
ret.append(self.curse_add_line(msg))
# STATUS
msg = '{0:>2}'.format('')
msg = '{:>2}'.format('')
ret.append(self.curse_add_line(msg))
# TIME+
msg = '{0:>10}'.format('')
msg = '{:>10}'.format('')
ret.append(self.curse_add_line(msg, optional=True))
# IO read/write
if 'io_counters' in self.stats[0] and mmm is None:
# IO read
io_rs = int((self.__sum_stats('io_counters', 0) - self.__sum_stats('io_counters', indice=2, mmm=mmm)) / self.stats[0]['time_since_update'])
if io_rs == 0:
msg = '{0:>6}'.format('0')
msg = '{:>6}'.format('0')
else:
msg = '{0:>6}'.format(self.auto_unit(io_rs, low_precision=True))
msg = '{:>6}'.format(self.auto_unit(io_rs, low_precision=True))
ret.append(self.curse_add_line(msg,
decoration=self.__mmm_deco(mmm),
optional=True, additional=True))
# IO write
io_ws = int((self.__sum_stats('io_counters', 1) - self.__sum_stats('io_counters', indice=3, mmm=mmm)) / self.stats[0]['time_since_update'])
if io_ws == 0:
msg = '{0:>6}'.format('0')
msg = '{:>6}'.format('0')
else:
msg = '{0:>6}'.format(self.auto_unit(io_ws, low_precision=True))
msg = '{:>6}'.format(self.auto_unit(io_ws, low_precision=True))
ret.append(self.curse_add_line(msg,
decoration=self.__mmm_deco(mmm),
optional=True, additional=True))
else:
msg = '{0:>6}'.format('')
msg = '{:>6}'.format('')
ret.append(self.curse_add_line(msg, optional=True, additional=True))
ret.append(self.curse_add_line(msg, optional=True, additional=True))
if mmm is None:
msg = ' < {0}'.format('current')
msg = ' < {}'.format('current')
ret.append(self.curse_add_line(msg, optional=True))
else:
msg = ' < {0}'.format(mmm)
msg = ' < {}'.format(mmm)
ret.append(self.curse_add_line(msg, optional=True))
msg = ' (\'M\' to reset)'
ret.append(self.curse_add_line(msg, optional=True))
......
......@@ -114,9 +114,9 @@ class Plugin(GlancesPlugin):
# Build the string message
if 'cpu_name' in self.stats and 'cpu_hz_current' in self.stats and 'cpu_hz' in self.stats:
msg_name = '{0} - '.format(self.stats['cpu_name'])
msg_freq = '{0:.2f}/{1:.2f}GHz'.format(self._hz_to_ghz(self.stats['cpu_hz_current']),
self._hz_to_ghz(self.stats['cpu_hz']))
msg_name = '{} - '.format(self.stats['cpu_name'])
msg_freq = '{:.2f}/{:.2f}GHz'.format(self._hz_to_ghz(self.stats['cpu_hz_current']),
self._hz_to_ghz(self.stats['cpu_hz']))
if len(msg_name + msg_freq) - 6 <= max_width:
ret.append(self.curse_add_line(msg_name))
ret.append(self.curse_add_line(msg_freq))
......@@ -126,13 +126,13 @@ class Plugin(GlancesPlugin):
for cpu in self.stats['percpu']:
bar.percent = cpu['total']
if cpu[cpu['key']] < 10:
msg = '{0:3}{1} '.format(key.upper(), cpu['cpu_number'])
msg = '{:3}{} '.format(key.upper(), cpu['cpu_number'])
else:
msg = '{0:4} '.format(cpu['cpu_number'])
msg = '{:4} '.format(cpu['cpu_number'])
ret.extend(self._msg_create_line(msg, bar, key))
else:
bar.percent = self.stats[key]
msg = '{0:4} '.format(key.upper())
msg = '{:4} '.format(key.upper())
ret.extend(self._msg_create_line(msg, bar, key))
# Return the message with decoration
......
......@@ -87,11 +87,11 @@ class Plugin(GlancesPlugin):
# Build the string message
# Header
msg = '{0:11}'.format('RAID disks')
msg = '{:11}'.format('RAID disks')
ret.append(self.curse_add_line(msg, "TITLE"))
msg = '{0:>6}'.format('Used')
msg = '{:>6}'.format('Used')
ret.append(self.curse_add_line(msg))
msg = '{0:>6}'.format('Avail')
msg = '{:>6}'.format('Avail')
ret.append(self.curse_add_line(msg))
# Data
arrays = sorted(iterkeys(self.stats))
......@@ -102,16 +102,16 @@ class Plugin(GlancesPlugin):
status = self.raid_alert(self.stats[array]['status'], self.stats[array]['used'], self.stats[array]['available'])
# Data: RAID type name | disk used | disk available
array_type = self.stats[array]['type'].upper() if self.stats[array]['type'] is not None else 'UNKNOWN'
msg = '{0:<5}{1:>6}'.format(array_type, array)
msg = '{:<5}{:>6}'.format(array_type, array)
ret.append(self.curse_add_line(msg))
if self.stats[array]['status'] == 'active':
msg = '{0:>6}'.format(self.stats[array]['used'])
msg = '{:>6}'.format(self.stats[array]['used'])
ret.append(self.curse_add_line(msg, status))
msg = '{0:>6}'.format(self.stats[array]['available'])
msg = '{:>6}'.format(self.stats[array]['available'])
ret.append(self.curse_add_line(msg, status))
elif self.stats[array]['status'] == 'inactive':
ret.append(self.curse_new_line())
msg = '└─ Status {0}'.format(self.stats[array]['status'])
msg = '└─ Status {}'.format(self.stats[array]['status'])
ret.append(self.curse_add_line(msg, status))
components = sorted(iterkeys(self.stats[array]['components']))
for i, component in enumerate(components):
......@@ -120,9 +120,9 @@ class Plugin(GlancesPlugin):
else:
tree_char = '├─'
ret.append(self.curse_new_line())
msg = ' {0} disk {1}: '.format(tree_char, self.stats[array]['components'][component])
msg = ' {} disk {}: '.format(tree_char, self.stats[array]['components'][component])
ret.append(self.curse_add_line(msg))
msg = '{0}'.format(component)
msg = '{}'.format(component)
ret.append(self.curse_add_line(msg))
if self.stats[array]['used'] < self.stats[array]['available']:
# Display current array configuration
......@@ -131,7 +131,7 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg, status))
if len(self.stats[array]['config']) < 17:
ret.append(self.curse_new_line())
msg = ' └─ {0}'.format(self.stats[array]['config'].replace('_', 'A'))
msg = ' └─ {}'.format(self.stats[array]['config'].replace('_', 'A'))
ret.append(self.curse_add_line(msg))
return ret
......
......@@ -179,7 +179,7 @@ class Plugin(GlancesPlugin):
# Build the string message
# Header
msg = '{0:18}'.format('SENSORS')
msg = '{:18}'.format('SENSORS')
ret.append(self.curse_add_line(msg, "TITLE"))
for i in self.stats:
......@@ -190,12 +190,12 @@ class Plugin(GlancesPlugin):
if label is None:
label = i['label']
if i['type'] != 'fan_speed':
msg = '{0:15}'.format(label[:15])
msg = '{:15}'.format(label[:15])
else:
msg = '{0:13}'.format(label[:13])
msg = '{:13}'.format(label[:13])
ret.append(self.curse_add_line(msg))
if i['value'] in (b'ERR', b'SLP', b'UNK'):
msg = '{0:>8}'.format(i['value'])
msg = '{:>8}'.format(i['value'])
ret.append(self.curse_add_line(
msg, self.get_views(item=i[self.get_key()],
key='value',
......@@ -209,7 +209,7 @@ class Plugin(GlancesPlugin):
value = i['value']
unit = i['unit']
try:
msg = '{0:>7.0f}{1}'.format(value, unit)
msg = '{:>7.0f}{}'.format(value, unit)
ret.append(self.curse_add_line(
msg, self.get_views(item=i[self.get_key()],
key='value',
......
......@@ -70,7 +70,7 @@ def _linux_os_release():
if 'NAME' in ashtray:
pretty_name = ashtray['NAME']
if 'VERSION_ID' in ashtray:
pretty_name += ' {0}'.format(ashtray['VERSION_ID'])
pretty_name += ' {}'.format(ashtray['VERSION_ID'])
return pretty_name
......@@ -133,9 +133,9 @@ class Plugin(GlancesPlugin):
if self.stats['os_name'] == "Linux":
self.stats['hr_name'] = self.stats['linux_distro']
else:
self.stats['hr_name'] = '{0} {1}'.format(
self.stats['hr_name'] = '{} {}'.format(
self.stats['os_name'], self.stats['os_version'])
self.stats['hr_name'] += ' {0}'.format(self.stats['platform'])
self.stats['hr_name'] += ' {}'.format(self.stats['platform'])
elif self.input_method == 'snmp':
# Update stats using SNMP
......@@ -180,17 +180,17 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg, "TITLE"))
# System info
if self.stats['os_name'] == "Linux" and self.stats['linux_distro']:
msg = ' ({0} {1} / {2} {3})'.format(self.stats['linux_distro'],
self.stats['platform'],
self.stats['os_name'],
self.stats['os_version'])
msg = ' ({} {} / {} {})'.format(self.stats['linux_distro'],
self.stats['platform'],
self.stats['os_name'],
self.stats['os_version'])
else:
try:
msg = ' ({0} {1} {2})'.format(self.stats['os_name'],
self.stats['os_version'],
self.stats['platform'])
msg = ' ({} {} {})'.format(self.stats['os_name'],
self.stats['os_version'],
self.stats['platform'])
except Exception:
msg = ' ({0})'.format(self.stats['os_name'])
msg = ' ({})'.format(self.stats['os_name'])
ret.append(self.curse_add_line(msg, optional=True))
# Return the message with decoration
......
......@@ -78,4 +78,4 @@ class Plugin(GlancesPlugin):
def msg_curse(self, args=None):
"""Return the string to display in the curse interface."""
return [self.curse_add_line('Uptime: {0}'.format(self.stats))]
return [self.curse_add_line('Uptime: {}'.format(self.stats))]
......@@ -467,8 +467,8 @@ class GlancesProcesses(object):
key=lambda x: x[1][self.sort_key],
reverse=self.sort_reverse)
except (KeyError, TypeError) as e:
logger.error("Cannot sort process list by {0}: {1}".format(self.sort_key, e))
logger.error('{0}'.format(listitems(processdict)[0]))
logger.error("Cannot sort process list by {}: {}".format(self.sort_key, e))
logger.error('{}'.format(listitems(processdict)[0]))
# Fallback to all process (issue #423)
processloop = iteritems(processdict)
first = False
......
......@@ -106,7 +106,7 @@ class GlancesXMLRPCServer(SimpleXMLRPCServer, object):
try:
self.address_family = socket.getaddrinfo(bind_address, bind_port)[0][0]
except socket.error as e:
logger.error("Couldn't open socket: {0}".format(e))
logger.error("Couldn't open socket: {}".format(e))
sys.exit(1)
super(GlancesXMLRPCServer, self).__init__((bind_address, bind_port), requestHandler)
......@@ -192,7 +192,7 @@ class GlancesServer(object):
try:
self.server = GlancesXMLRPCServer(args.bind_address, args.port, requestHandler)
except Exception as e:
logger.critical("Cannot start Glances server: {0}".format(e))
logger.critical("Cannot start Glances server: {}".format(e))
sys.exit(2)
# The users dict
......
......@@ -122,5 +122,6 @@ class GlancesStandalone(object):
# Check Glances version versus Pypi one
if self.outdated.is_outdated():
print("You are using Glances version {0}, however version {1} is available.".format(self.outdated.installed_version(), self.outdated.latest_version()))
print("You are using Glances version {}, however version {} is available.".format(
self.outdated.installed_version(), self.outdated.latest_version()))
print("You should consider upgrading using: pip install --upgrade glances")
......@@ -102,7 +102,7 @@ class GlancesStats(object):
else:
self._plugins[plugin_name] = plugin.Plugin(args=args)
# Log plugins list
logger.debug("Available plugins list: {0}".format(self.getAllPlugins()))
logger.debug("Available plugins list: {}".format(self.getAllPlugins()))
def load_exports(self, args=None):
"""Load all export modules in the 'exports' folder."""
......@@ -128,7 +128,7 @@ class GlancesStats(object):
# generate self._exports_list["xxx"] = ...
self._exports[export_name] = export_module.Export(args=args, config=self.config)
# Log plugins list
logger.debug("Available exports modules list: {0}".format(self.getExportList()))
logger.debug("Available exports modules list: {}".format(self.getExportList()))
return True
def getAllPlugins(self):
......
......@@ -50,7 +50,7 @@ class GlancesStatsClient(GlancesStats):
# The key is the plugin name
# for example, the file glances_xxx.py
# generate self._plugins_list["xxx"] = ...
logger.debug("Server uses {0} plugin".format(item))
logger.debug("Server uses {} plugin".format(item))
self._plugins[item] = plugin.Plugin()
# Restoring system path
sys.path = sys_path
......
......@@ -74,7 +74,7 @@ class GlancesStatsClientSNMP(GlancesStats):
oid_os_name = clientsnmp.get_by_oid("1.3.6.1.2.1.1.1.0")
try:
self.system_name = self.get_system_name(oid_os_name['1.3.6.1.2.1.1.1.0'])
logger.info("SNMP system name detected: {0}".format(self.system_name))
logger.info("SNMP system name detected: {}".format(self.system_name))
except KeyError:
self.system_name = None
logger.warning("Cannot detect SNMP system name")
......@@ -106,4 +106,4 @@ class GlancesStatsClientSNMP(GlancesStats):
try:
self._plugins[p].update()
except Exception as e:
logger.error("Update {0} failed: {1}".format(p, e))
logger.error("Update {} failed: {}".format(p, e))
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册