Use parentheses sparingly in conditional statements

Mandatory only for multi-line continuation
This commit is contained in:
Alessio Sergi 2014-04-23 12:23:23 +02:00
parent 3012662a92
commit 6e7c3a275e
27 changed files with 169 additions and 177 deletions

View File

@ -25,7 +25,7 @@ import signal
import sys
# Import Glances libs
# Note: others Glances libs will be imported optionnaly
# Note: others Glances libs will be imported optionally
from glances.core.glances_main import GlancesMain
@ -41,13 +41,13 @@ def end():
Stop Glances
"""
if (core.is_standalone()):
if core.is_standalone():
# Stop the standalone (CLI)
standalone.end()
elif (core.is_client()):
elif core.is_client():
# Stop the client
client.end()
elif (core.is_server()):
elif core.is_server():
# Stop the server
server.end()
@ -72,7 +72,7 @@ def main():
signal.signal(signal.SIGINT, __signal_handler)
# Glances can be ran in standalone, client or server mode
if (core.is_standalone()):
if core.is_standalone():
# Import the Glances standalone module
from glances.core.glances_standalone import GlancesStandalone
@ -84,7 +84,7 @@ def main():
# Start the standalone (CLI) loop
standalone.serve_forever()
elif (core.is_client()):
elif core.is_client():
# Import the Glances client module
from glances.core.glances_client import GlancesClient
@ -94,7 +94,7 @@ def main():
args=core.get_args())
# Test if client and server are in the same major version
if (not client.login()):
if not client.login():
print(_("Error: The server version is not compatible with the client"))
sys.exit(2)
@ -104,7 +104,7 @@ def main():
# Shutdown the client
client.close()
elif (core.is_server()):
elif core.is_server():
# Import the Glances server module
from glances.core.glances_server import GlancesServer
@ -117,7 +117,7 @@ def main():
print(_("Glances server is running on {0}:{1}").format(args.bind_address, args.port))
# Set the server login/password (if -P/--password tag)
if (args.password != ""):
if args.password != "":
server.add_user(args.username, args.password)
# Start the server loop
@ -126,7 +126,7 @@ def main():
# Shutdown the server?
server.server_close()
elif (core.is_webserver()):
elif core.is_webserver():
# Import the Glances web server module
from glances.core.glances_webserver import GlancesWebServer

View File

@ -18,16 +18,15 @@
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Execute with
# $ python glances/__main__.py (2.6+)
"""Allow user to run Glances as a module from a dir or zip file."""
# Execute with:
# $ python glances/__main__.py (2.6)
# $ python -m glances (2.7+)
"""
Allow user to run Glances as a module from a dir or zip file
"""
import sys
if ((__package__ is None) and (not hasattr(sys, "frozen"))):
if __package__ is None and not hasattr(sys, "frozen"):
# It is a direct call to __main__.py
import os.path
path = os.path.realpath(os.path.abspath(__file__))

View File

@ -40,15 +40,13 @@ class GlancesClient():
This class creates and manages the TCP client
"""
def __init__(self,
config=None,
args=None):
def __init__(self, config=None, args=None):
# Store the arg/config
self.args = args
self.config = config
# Build the URI
if (args.password != ""):
if args.password != "":
uri = 'http://%s:%s@%s:%d' % (args.username, args.password, args.bind_address, args.port)
else:
uri = 'http://%s:%d' % (args.bind_address, args.port)
@ -70,14 +68,14 @@ class GlancesClient():
print(_("Error: Connection to server failed: {0}").format(err))
sys.exit(2)
except ProtocolError as err:
if (str(err).find(" 401 ") > 0):
if str(err).find(" 401 ") > 0:
print(_("Error: Connection to server failed: Bad password"))
else:
print(_("Error: Connection to server failed: {0}").format(err))
sys.exit(2)
# Test if client and server are "compatible"
if (__version__[:3] == client_version[:3]):
if __version__[:3] == client_version[:3]:
# Init stats
self.stats = GlancesStatsClient()
self.stats.set_plugins(json.loads(self.client.getAllPlugins()))

View File

@ -56,7 +56,7 @@ class Config(object):
Load a config file from the list of paths, if it exists
"""
for path in self.get_paths_list():
if (os.path.isfile(path) and os.path.getsize(path) > 0):
if os.path.isfile(path) and os.path.getsize(path) > 0:
try:
if is_python3:
self.parser.read(path, encoding='utf-8')

View File

@ -41,7 +41,7 @@ psutil_version = tuple([int(num) for num in __psutil_version__.split('.')])
# Check psutil version
psutil_min_version = (2, 0, 0)
if (psutil_version < psutil_min_version):
if psutil_version < psutil_min_version:
print('psutil version %s detected.' % __psutil_version__)
print('psutil 2.0 or higher is needed. Glances cannot start.')
sys.exit(1)

View File

@ -18,8 +18,8 @@
# along with this program. If not, see <http://www.gnu.org/licenses/>.
# Import system libs
from datetime import datetime
import time
from datetime import datetime
# Import Glances libs
from glances.core.glances_globals import glances_processes
@ -75,7 +75,7 @@ class glancesLogs:
-1 if the item is not found
"""
for i in range(self.len()):
if ((self.logs_list[i][1] < 0) and (self.logs_list[i][3] == item_type)):
if self.logs_list[i][1] < 0 and self.logs_list[i][3] == item_type:
return i
return -1
@ -84,10 +84,10 @@ class glancesLogs:
Define the process auto sort key from the alert type
"""
# Process sort depending on alert type
if (item_type.startswith("MEM")):
if item_type.startswith("MEM"):
# Sort TOP process by memory_percent
process_auto_by = 'memory_percent'
elif (item_type.startswith("CPU_IOWAIT")):
elif item_type.startswith("CPU_IOWAIT"):
# Sort TOP process by io_counters (only for Linux OS)
process_auto_by = 'io_counters'
else:
@ -118,9 +118,9 @@ class glancesLogs:
"""
# Add or update the log
item_index = self.__itemexist__(item_type)
if (item_index < 0):
if item_index < 0:
# Item did not exist, add if WARNING or CRITICAL
if ((item_state == "WARNING") or (item_state == "CRITICAL")):
if item_state == "WARNING" or item_state == "CRITICAL":
# Define the automatic process sort key
self.set_process_sort(item_type)
@ -152,7 +152,7 @@ class glancesLogs:
self.logs_list.pop()
else:
# Item exist, update
if ((item_state == "OK") or (item_state == "CAREFUL")):
if item_state == "OK" or item_state == "CAREFUL":
# Reset the automatic process sort key
self.reset_process_sort()
@ -162,13 +162,13 @@ class glancesLogs:
else:
# Update the item
# State
if (item_state == "CRITICAL"):
if item_state == "CRITICAL":
self.logs_list[item_index][2] = item_state
# Value
if (item_value > self.logs_list[item_index][4]):
if item_value > self.logs_list[item_index][4]:
# MAX
self.logs_list[item_index][4] = item_value
elif (item_value < self.logs_list[item_index][6]):
elif item_value < self.logs_list[item_index][6]:
# MIN
self.logs_list[item_index][6] = item_value
# AVG
@ -199,7 +199,7 @@ class glancesLogs:
clean_logs_list = []
while (self.len() > 0):
item = self.logs_list.pop()
if ((item[1] < 0) or (not critical and (item[2].startswith("CRITICAL")))):
if item[1] < 0 or (not critical and item[2].startswith("CRITICAL")):
clean_logs_list.insert(0, item)
# The list is now the clean one
self.logs_list = clean_logs_list

View File

@ -50,8 +50,7 @@ class monitorList:
self.config = config
if ((self.config != None)
and self.config.has_section('monitor')):
if self.config is not None and self.config.has_section('monitor'):
# Process monitoring list
self.__setMonitorList('monitor', 'list')
else:
@ -75,8 +74,7 @@ class monitorList:
print(_("Error reading monitored list: %s" % e))
pass
else:
if ((description is not None) and
(regex is not None)):
if description is not None and regex is not None:
# Build the new item
value["description"] = description
value["regex"] = regex
@ -105,7 +103,7 @@ class monitorList:
Meta function to return key value of item
None if not defined or item > len(list)
"""
if (item < len(self.__monitor_list)):
if item < len(self.__monitor_list):
try:
return self.__monitor_list[item][key]
except Exception:
@ -119,7 +117,7 @@ class monitorList:
"""
# Only continue if monitor list is not empty
if (len(self.__monitor_list) == 0):
if len(self.__monitor_list) == 0:
return self.__monitor_list
# Iter uppon the monitored list
@ -129,7 +127,7 @@ class monitorList:
monitoredlist = [p for p in processlist if re.search(self.regex(i), p['cmdline']) is not None]
self.__monitor_list[i]['count'] = len(monitoredlist)
if (self.command(i) is None):
if self.command(i) is None:
# If there is no command specified in the conf file
# then display CPU and MEM %
self.__monitor_list[i]['result'] = "CPU: {0:.1f}% | MEM: {1:.1f}%".format(

View File

@ -166,7 +166,7 @@ class glancesProcesses:
self.processcount = {'total': 0, 'running': 0, 'sleeping': 0, 'thread': 0}
# Do not process if disable tag is set
if (self.disable_tag):
if self.disable_tag:
return
# Get the time since last update
@ -183,8 +183,8 @@ class glancesProcesses:
# ignore the 'kernel_task' process on OS X
# waiting for upstream patch from psutil
if (is_BSD and procstat['name'] == 'idle' or
is_Windows and procstat['name'] == 'System Idle Process' or
is_Mac and procstat['name'] == 'kernel_task'):
is_Windows and procstat['name'] == 'System Idle Process' or
is_Mac and procstat['name'] == 'kernel_task'):
continue
# Update processcount (global statistics)
try:
@ -206,7 +206,7 @@ class glancesProcesses:
self.processlist.append(procstat)
# Clean internals caches if timeout is reached
if (self.cache_timer.finished()):
if self.cache_timer.finished():
self.username_cache = {}
self.cmdline_cache = {}
# Restart the timer
@ -238,15 +238,15 @@ class glancesProcesses:
"""
Return the processlist
"""
if (sortedby is None):
if sortedby is None:
# No need to sort...
return self.processlist
sortedreverse = True
if (sortedby == 'name'):
if sortedby == 'name':
sortedreverse = False
if (sortedby == 'io_counters'):
if sortedby == 'io_counters':
# Specific case for io_counters
# Sum of io_r + io_w
try:

View File

@ -171,7 +171,7 @@ class GlancesInstance():
# print "DEBUG: Call method: %s" % item
header = 'get'
# Check if the attribute starts with 'get'
if (item.startswith(header)):
if item.startswith(header):
try:
# Update the stat
# !!! All the stat are updated before one grab (not optimized)

View File

@ -49,12 +49,12 @@ class GlancesStats(object):
"""
# Check if the attribute starts with 'get'
if (item.startswith('get')):
if item.startswith('get'):
# Get the plugin name
plugname = item[len('get'):].lower()
# Get the plugin instance
plugin = self._plugins[plugname]
if (hasattr(plugin, 'get_stats')):
if hasattr(plugin, 'get_stats'):
# The method get_stats exist, return it
return getattr(plugin, 'get_stats')
else:
@ -75,8 +75,9 @@ class GlancesStats(object):
header = "glances_"
for plug in os.listdir(plug_dir):
if (plug.startswith(header) and plug.endswith(".py") and
plug != (header + "plugin.py")):
if (plug.startswith(header) and
plug.endswith(".py") and
plug != (header + "plugin.py")):
# Import the plugin
m = __import__(os.path.basename(plug)[:-3])
# Add the plugin to the dictionnary
@ -101,7 +102,7 @@ class GlancesStats(object):
Update the stats
"""
if (input_stats == {}):
if input_stats == {}:
# For standalone and server modes
# For each plugins, call the update method
for p in self._plugins:
@ -123,7 +124,7 @@ class GlancesStats(object):
def get_plugin(self, plugin_name):
# Return the plugin name
if (plugin_name in self._plugins):
if plugin_name in self._plugins:
return self._plugins[plugin_name]
else:
return None

View File

@ -68,7 +68,6 @@ class glancesBottle:
'CRITICAL_LOG': 'critical_log'
}
def _route(self):
"""
Define route
@ -83,7 +82,7 @@ class glancesBottle:
self.stats = stats
# Start the Bottle
self._app.run(host=self.args.bind, port=self.args.port)
self._app.run(host=self.args.bind_address, port=self.args.port)
def end(self):
# End the Bottle
@ -94,7 +93,7 @@ class glancesBottle:
Bottle callback for index.html (/) file
"""
# Manage parameter
if (refresh_time is None):
if refresh_time is None:
refresh_time = self.args.time
# Update the stat
@ -171,16 +170,16 @@ class glancesBottle:
tpl += '<div class="row">'
for m in plugin_stats['msgdict']:
# New line
if (m['msg'].startswith('\n')):
if m['msg'].startswith('\n'):
tpl += '</div>'
tpl += '<div class="row">'
continue
# Do not display splittable
if (m['splittable']):
if m['splittable']:
tpl += '<span></span>'
continue
tpl += '<span class="cell" id="%s">%s</span>' % (self.__style_list[m['decoration']] ,
m['msg'].replace(' ', '&nbsp;'))
tpl += '<span class="cell" id="%s">%s</span>' % \
(self.__style_list[m['decoration']], m['msg'].replace(' ', '&nbsp;'))
tpl += '</div>'
tpl += '</div>'

View File

@ -235,7 +235,7 @@ class glancesCurses:
# Enable/Disable display
self.args.disable_process = not self.args.disable_process
# Enable/Disable update
if (self.args.disable_process):
if self.args.disable_process:
glances_processes.disable()
else:
glances_processes.enable()
@ -272,7 +272,7 @@ class glancesCurses:
screen_x = self.screen.getmaxyx()[1]
screen_y = self.screen.getmaxyx()[0]
if (self.args.help_tag):
if self.args.help_tag:
# Display the stats...
self.display_plugin(stats.get_plugin('help').get_stats_display(args=self.args))
# ... and exit
@ -290,7 +290,7 @@ class glancesCurses:
# Display second line (CPU|PERCPU+LOAD+MEM+SWAP+<SUMMARY>)
# CPU|PERCPU
if (self.args.percpu):
if self.args.percpu:
stats_percpu = stats.get_plugin('percpu').get_stats_display()
l = self.get_stats_display_width(stats_percpu)
else:
@ -301,10 +301,10 @@ class glancesCurses:
stats_memswap = stats.get_plugin('memswap').get_stats_display()
l += self.get_stats_display_width(stats_load) + self.get_stats_display_width(stats_mem) + self.get_stats_display_width(stats_memswap)
# Space between column
if (screen_x > (3 * self.space_between_column + l)):
if screen_x > (3 * self.space_between_column + l):
self.space_between_column = int((screen_x - l) / 3)
# Display
if (self.args.percpu):
if self.args.percpu:
self.display_plugin(stats_percpu)
else:
self.display_plugin(stats_cpu, display_optional=(screen_x >= 76))
@ -323,7 +323,7 @@ class glancesCurses:
self.display_plugin(stats.get_plugin('now').get_stats_display())
# Display right sidebar (PROCESS_COUNT+MONITORED+PROCESS_LIST+ALERT)
if (screen_x > 52):
if screen_x > 52:
stats_processcount = stats.get_plugin('processcount').get_stats_display(args=self.args)
stats_processlist = stats.get_plugin('processlist').get_stats_display(args=self.args)
stats_alert = stats.get_plugin('alert').get_stats_display(args=self.args)
@ -345,8 +345,7 @@ class glancesCurses:
# Exit if:
# - the plugin_stats message is empty
# - the display tag = False
if ((plugin_stats['msgdict'] == [])
or (not plugin_stats['display'])):
if plugin_stats['msgdict'] == [] or not plugin_stats['display']:
# Display the next plugin at the current plugin position
try:
self.column_to_x[plugin_stats['column'] + 1] = self.column_to_x[plugin_stats['column']]
@ -361,18 +360,18 @@ class glancesCurses:
screen_y = self.screen.getmaxyx()[0]
# Set the upper/left position of the message
if (plugin_stats['column'] < 0):
if plugin_stats['column'] < 0:
# Right align (last column)
display_x = screen_x - self.get_stats_display_width(plugin_stats)
else:
if (plugin_stats['column'] not in self.column_to_x):
if plugin_stats['column'] not in self.column_to_x:
self.column_to_x[plugin_stats['column']] = plugin_stats['column']
display_x = self.column_to_x[plugin_stats['column']]
if (plugin_stats['line'] < 0):
if plugin_stats['line'] < 0:
# Bottom (last line)
display_y = screen_y - self.get_stats_display_height(plugin_stats)
else:
if (plugin_stats['line'] not in self.line_to_y):
if plugin_stats['line'] not in self.line_to_y:
self.line_to_y[plugin_stats['line']] = plugin_stats['line']
display_y = self.line_to_y[plugin_stats['line']]
@ -381,21 +380,21 @@ class glancesCurses:
y = display_y
for m in plugin_stats['msgdict']:
# New line
if (m['msg'].startswith('\n')):
if m['msg'].startswith('\n'):
# Go to the next line
y = y + 1
# Return to the first column
x = display_x
continue
# Do not display outside the screen
if (x < 0):
if x < 0:
continue
if ((not m['splittable']) and (x + len(m['msg']) > screen_x)):
if not m['splittable'] and (x + len(m['msg']) > screen_x):
continue
if ((y < 0) or (y + 1 > screen_y) or (y > max_y)):
if y < 0 or (y + 1 > screen_y) or (y > max_y):
break
# If display_optional = False do not display optional stats
if ((not display_optional) and m['optional']):
if not display_optional and m['optional']:
continue
# Is it possible to display the stat with the current screen size
# !!! Crach if not try/except... Why ???
@ -411,9 +410,9 @@ class glancesCurses:
x = x + len(m['msg'])
# Compute the next Glances column/line position
if (plugin_stats['column'] > -1):
if plugin_stats['column'] > -1:
self.column_to_x[plugin_stats['column'] + 1] = x + self.space_between_column
if (plugin_stats['line'] > -1):
if plugin_stats['line'] > -1:
self.line_to_y[plugin_stats['line'] + 1] = y + self.space_between_line
def erase(self):
@ -459,7 +458,7 @@ class glancesCurses:
# The height is defined by the maximum line
try:
if (without_option):
if without_option:
# Size without options
c = len(max(''.join([(i['msg'] if not i['optional'] else "")
for i in curse_msg['msgdict']]).split('\n'), key=len))

View File

@ -60,12 +60,12 @@ class Plugin(GlancesPlugin):
ret = []
# Only process if display plugin enable...
if (args.disable_log):
if args.disable_log:
return ret
# Build the string message
# Header
if (self.stats == []):
if self.stats == []:
msg = "{0}".format(_("No warning or critical alert detected"))
ret.append(self.curse_add_line(msg, "TITLE"))
else:
@ -73,7 +73,7 @@ class Plugin(GlancesPlugin):
msg = "{0}".format(_("Warning or critical alerts"))
ret.append(self.curse_add_line(msg, "TITLE"))
logs_len = glances_logs.len()
if (logs_len > 1):
if logs_len > 1:
msg = " {0}".format(_("(lasts %s entries)") % logs_len)
else:
msg = " {0}".format(_("(one entry)"))
@ -86,7 +86,7 @@ class Plugin(GlancesPlugin):
msg = "{0}".format(datetime.fromtimestamp(alert[0]))
ret.append(self.curse_add_line(msg))
# Duration
if (alert[1] > 0):
if alert[1] > 0:
# If finished display duration
msg = " ({0})".format(datetime.fromtimestamp(alert[1]) - datetime.fromtimestamp(alert[0]))
else:
@ -94,7 +94,7 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg))
ret.append(self.curse_add_line(" - "))
# Infos
if (alert[1] > 0):
if alert[1] > 0:
# If finished do not display status
msg = "{0} {1} {2}".format(alert[2], _("on"), alert[3])
ret.append(self.curse_add_line(msg))
@ -102,7 +102,7 @@ class Plugin(GlancesPlugin):
msg = "{0}".format(alert[3])
ret.append(self.curse_add_line(msg, decoration=alert[2]))
# Min / Mean / Max
if (alert[6] == alert[4]):
if alert[6] == alert[4]:
msg = " ({0:.1f})".format(alert[5])
else:
msg = " (Min:{0:.1f} Mean:{1:.1f} Max:{2:.1f})".format(alert[6], alert[5], alert[4])

View File

@ -72,7 +72,7 @@ class Plugin(GlancesPlugin):
for cpu in ['user', 'system', 'idle', 'nice',
'iowait', 'irq', 'softirq', 'steal',
'guest', 'guest_nice']:
if (hasattr(cputimespercent, cpu)):
if hasattr(cputimespercent, cpu):
cpu_stats[cpu] = getattr(cputimespercent, cpu)
# Set the global variable to the new stats
@ -89,7 +89,7 @@ class Plugin(GlancesPlugin):
ret = []
# Only process if stats exist...
if (self.stats == {}):
if self.stats == {}:
return ret
# Build the string message
@ -101,7 +101,7 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg))
# Steal CPU usage
# ret.append(self.curse_add_line(" ", optional=True))
if ('steal' in self.stats):
if 'steal' in self.stats:
msg = " {0:8}".format(_("steal:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.stats['steal'] / 100, '>6.1%'))
@ -109,14 +109,14 @@ class Plugin(GlancesPlugin):
# New line
ret.append(self.curse_new_line())
# User CPU
if ('user' in self.stats):
if 'user' in self.stats:
msg = "{0:8}".format(_("user:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.stats['user'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, self.get_alert_log(self.stats['user'], header="user")))
# IOWait CPU
# ret.append(self.curse_add_line(" ", optional=True))
if ('iowait' in self.stats):
if 'iowait' in self.stats:
msg = " {0:8}".format(_("iowait:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.stats['iowait'] / 100, '>6.1%'))
@ -124,14 +124,14 @@ class Plugin(GlancesPlugin):
# New line
ret.append(self.curse_new_line())
# System CPU
if ('system' in self.stats):
if 'system' in self.stats:
msg = "{0:8}".format(_("system:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.stats['system'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg, self.get_alert_log(self.stats['system'], header="system")))
# IRQ CPU
# ret.append(self.curse_add_line(" ", optional=True))
if ('irq' in self.stats):
if 'irq' in self.stats:
msg = " {0:8}".format(_("irq:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.stats['irq'] / 100, '>6.1%'))
@ -139,14 +139,14 @@ class Plugin(GlancesPlugin):
# New line
ret.append(self.curse_new_line())
# Nice CPU
if ('nice' in self.stats):
if 'nice' in self.stats:
msg = "{0:8}".format(_("nice:"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(format(self.stats['nice'] / 100, '>6.1%'))
ret.append(self.curse_add_line(msg))
# Idles CPU
# ret.append(self.curse_add_line(" ", optional=True))
if ('idle' in self.stats):
if 'idle' in self.stats:
msg = " {0:8}".format(_("idle:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0}".format(format(self.stats['idle'] / 100, '>6.1%'))

View File

@ -65,7 +65,7 @@ class Plugin(GlancesPlugin):
# Previous disk IO stats are stored in the diskio_old variable
diskio = []
if (self.diskio_old == []):
if self.diskio_old == []:
# First call, we init the network_old var
try:
self.diskio_old = diskiocounters
@ -109,7 +109,7 @@ class Plugin(GlancesPlugin):
ret = []
# Only process if stats exist and display plugin enable...
if ((self.stats == []) or (args.disable_diskio)):
if self.stats == [] or args.disable_diskio:
return ret
# Build the string message
@ -123,7 +123,7 @@ class Plugin(GlancesPlugin):
# Disk list (sorted by name)
for i in sorted(self.stats, key=lambda diskio: diskio['disk_name']):
# Do not display hidden interfaces
if (self.is_hide(i['disk_name'])):
if self.is_hide(i['disk_name']):
continue
# New line
ret.append(self.curse_new_line())

View File

@ -109,7 +109,7 @@ class Plugin(GlancesPlugin):
ret = []
# Only process if stats exist and display plugin enable...
if ((self.stats == []) or (args.disable_fs)):
if self.stats == [] or args.disable_fs:
return ret
# Build the string message
@ -125,10 +125,10 @@ class Plugin(GlancesPlugin):
for i in sorted(self.stats, key=lambda fs: fs['mnt_point']):
# New line
ret.append(self.curse_new_line())
if ((len(i['mnt_point']) + len(i['device_name'].split('/')[-1])) <= 6):
if (len(i['mnt_point']) + len(i['device_name'].split('/')[-1])) <= 6:
# If possible concatenate mode info... Glances touch inside :)
mnt_point = i['mnt_point'] + ' (' + i['device_name'].split('/')[-1] + ')'
elif (len(i['mnt_point']) > 9):
elif len(i['mnt_point']) > 9:
# Cut mount point name if it is too long
mnt_point = '_' + i['mnt_point'][-8:]
else:

View File

@ -79,7 +79,7 @@ class Plugin(GlancesPlugin):
ret = []
# Only process if stats exist...
if (self.stats == {}):
if self.stats == {}:
return ret
# Build the string message

View File

@ -69,15 +69,15 @@ class Plugin(GlancesPlugin):
for mem in ['total', 'available', 'percent', 'used', 'free',
'active', 'inactive', 'buffers', 'cached',
'wired', 'shared']:
if (hasattr(vm_stats, mem)):
if hasattr(vm_stats, mem):
mem_stats[mem] = getattr(vm_stats, mem)
# Use the 'free'/htop calculation
# free=available+buffer+cached
mem_stats['free'] = mem_stats['available']
if (hasattr(mem_stats, 'buffer')):
if hasattr(mem_stats, 'buffer'):
mem_stats['free'] += mem_stats['buffer']
if (hasattr(mem_stats, 'cached')):
if hasattr(mem_stats, 'cached'):
mem_stats['free'] += mem_stats['cached']
# used=total-free
mem_stats['used'] = mem_stats['total'] - mem_stats['free']
@ -95,7 +95,7 @@ class Plugin(GlancesPlugin):
ret = []
# Only process if stats exist...
if (self.stats == {}):
if self.stats == {}:
return ret
# Build the string message
@ -106,7 +106,7 @@ class Plugin(GlancesPlugin):
msg = "{0:>6}%".format(format(self.stats['percent'] / 100, '.1'))
ret.append(self.curse_add_line(msg))
# Active memory usage
if ('active' in self.stats):
if 'active' in self.stats:
msg = " {0:8}".format(_("actif:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0:>7}".format(self.auto_unit(self.stats['active']))
@ -119,7 +119,7 @@ class Plugin(GlancesPlugin):
msg = "{0:>7}".format(self.auto_unit(format(self.stats['total']), '.1%'))
ret.append(self.curse_add_line(msg))
# Inactive memory usage
if ('inactive' in self.stats):
if 'inactive' in self.stats:
msg = " {0:8}".format(_("inactif:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0:>7}".format(self.auto_unit(self.stats['inactive']))
@ -131,10 +131,9 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg))
msg = "{0:>7}".format(self.auto_unit(self.stats['used']))
ret.append(self.curse_add_line(
msg, self.get_alert_log(self.stats['used'],
max=self.stats['total'])))
msg, self.get_alert_log(self.stats['used'], max=self.stats['total'])))
# Buffers memory usage
if ('buffers' in self.stats):
if 'buffers' in self.stats:
msg = " {0:8}".format(_("buffers:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0:>7}".format(self.auto_unit(self.stats['buffers']))
@ -147,7 +146,7 @@ class Plugin(GlancesPlugin):
msg = "{0:>7}".format(self.auto_unit(self.stats['free']))
ret.append(self.curse_add_line(msg))
# Cached memory usage
if ('cached' in self.stats):
if 'cached' in self.stats:
msg = " {0:8}".format(_("cached:"))
ret.append(self.curse_add_line(msg, optional=True))
msg = "{0:>7}".format(self.auto_unit(self.stats['cached']))

View File

@ -62,7 +62,7 @@ class Plugin(GlancesPlugin):
swap_stats = {}
for swap in ['total', 'used', 'free', 'percent',
'sin', 'sout']:
if (hasattr(sm_stats, swap)):
if hasattr(sm_stats, swap):
swap_stats[swap] = getattr(sm_stats, swap)
# Set the global variable to the new stats
@ -78,7 +78,7 @@ class Plugin(GlancesPlugin):
ret = []
# Only process if stats exist...
if (self.stats == {}):
if self.stats == {}:
return ret
# Build the string message
@ -102,8 +102,7 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg))
msg = "{0:>6}".format(self.auto_unit(self.stats['used']))
ret.append(self.curse_add_line(
msg, self.get_alert_log(self.stats['used'],
max=self.stats['total'])))
msg, self.get_alert_log(self.stats['used'], max=self.stats['total'])))
# New line
ret.append(self.curse_new_line())
# Free memory usage

View File

@ -55,7 +55,7 @@ class Plugin(GlancesPlugin):
Update the monitored list
"""
# Check if the glances_monitor instance is init
if (self.glances_monitors == None):
if self.glances_monitors is None:
return self.stats
# Update the monitored list (result of command)
@ -68,19 +68,19 @@ class Plugin(GlancesPlugin):
def get_alert(self, nbprocess=0, countmin=None, countmax=None, header="", log=False):
# Return the alert status relative to the process number
if (nbprocess is None):
if nbprocess is None:
return 'OK'
if (countmin is None):
if countmin is None:
countmin = nbprocess
if (countmax is None):
if countmax is None:
countmax = nbprocess
if (nbprocess > 0):
if (int(countmin) <= int(nbprocess) <= int(countmax)):
if nbprocess > 0:
if int(countmin) <= int(nbprocess) <= int(countmax):
return 'OK'
else:
return 'WARNING'
else:
if (int(countmin) == 0):
if int(countmin) == 0:
return 'OK'
else:
return 'CRITICAL'
@ -93,7 +93,7 @@ class Plugin(GlancesPlugin):
ret = []
# Only process if stats exist and display plugin enable...
if ((self.stats == []) or (args.disable_process)):
if self.stats == [] or args.disable_process:
return ret
# Build the string message
@ -101,11 +101,11 @@ class Plugin(GlancesPlugin):
msg = "{0:<16} ".format(str(m['description']))
ret.append(self.curse_add_line(
msg, self.get_alert(m['count'], m['countmin'], m['countmax'])))
msg = "{0:<3} ".format(m['count'] if (m['count'] > 1) else "")
msg = "{0:<3} ".format(m['count'] if m['count'] > 1 else "")
ret.append(self.curse_add_line(msg))
msg = "{0:13} ".format(_("RUNNING") if (m['count'] >= 1) else _("NOT RUNNING"))
msg = "{0:13} ".format(_("RUNNING") if m['count'] >= 1 else _("NOT RUNNING"))
ret.append(self.curse_add_line(msg))
msg = "{0}".format(m['result'] if (m['count'] >= 1) else "")
msg = "{0}".format(m['result'] if m['count'] >= 1 else "")
ret.append(self.curse_add_line(msg))
ret.append(self.curse_new_line())

View File

@ -61,7 +61,7 @@ class Plugin(GlancesPlugin):
# Previous network interface stats are stored in the network_old variable
network = []
if (self.network_old == []):
if self.network_old == []:
# First call, we init the network_old var
try:
self.network_old = netiocounters
@ -112,16 +112,16 @@ class Plugin(GlancesPlugin):
ret = []
# Only process if stats exist and display plugin enable...
if ((self.stats == []) or (args.disable_network)):
if self.stats == [] or args.disable_network:
return ret
# Build the string message
# Header
msg = "{0:9}".format(_("NETWORK"))
ret.append(self.curse_add_line(msg, "TITLE"))
if (args.network_cumul):
if args.network_cumul:
# Cumulative stats
if (args.network_sum):
if args.network_sum:
# Sum stats
msg = "{0:>14}".format(_("Rx+Tx"))
ret.append(self.curse_add_line(msg))
@ -133,7 +133,7 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg))
else:
# Bitrate stats
if (args.network_sum):
if args.network_sum:
# Sum stats
msg = "{0:>14}".format(_("Rx+Tx/s"))
ret.append(self.curse_add_line(msg))
@ -145,12 +145,12 @@ class Plugin(GlancesPlugin):
# Interface list (sorted by name)
for i in sorted(self.stats, key=lambda network: network['interface_name']):
# Do not display hidden interfaces
if (self.is_hide(i['interface_name'])):
if self.is_hide(i['interface_name']):
continue
# Format stats
ifname = i['interface_name'].split(':')[0]
if (args.byte):
if (args.network_cumul):
if args.byte:
if args.network_cumul:
rx = self.auto_unit(int(i['cumulative_rx']))
tx = self.auto_unit(int(i['cumulative_tx']))
sx = self.auto_unit(int(i['cumulative_tx'])
@ -161,7 +161,7 @@ class Plugin(GlancesPlugin):
sx = self.auto_unit(int(i['rx'] // i['time_since_update'])
+ int(i['tx'] // i['time_since_update']))
else:
if (args.network_cumul):
if args.network_cumul:
rx = self.auto_unit(int(i['cumulative_rx'] * 8)) + "b"
tx = self.auto_unit(int(i['cumulative_tx'] * 8)) + "b"
sx = self.auto_unit(int(i['cumulative_rx'] * 8)
@ -175,7 +175,7 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_new_line())
msg = "{0:9}".format(ifname)
ret.append(self.curse_add_line(msg))
if (args.network_sum):
if args.network_sum:
msg = "{0:>14}".format(sx)
ret.append(self.curse_add_line(msg))
else:

View File

@ -139,7 +139,7 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg))
# User CPU
if ('user' in self.stats[0]):
if 'user' in self.stats[0]:
# New line
ret.append(self.curse_new_line())
msg = "{0:8}".format(_("user:"))
@ -149,7 +149,7 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg, self.get_alert(cpu['user'], header="user")))
# System CPU
if ('user' in self.stats[0]):
if 'user' in self.stats[0]:
# New line
ret.append(self.curse_new_line())
msg = "{0:8}".format(_("system:"))
@ -159,7 +159,7 @@ class Plugin(GlancesPlugin):
ret.append(self.curse_add_line(msg, self.get_alert(cpu['system'], header="system")))
# IoWait CPU
if ('user' in self.stats[0]):
if 'user' in self.stats[0]:
# New line
ret.append(self.curse_new_line())
msg = "{0:8}".format(_("iowait:"))

View File

@ -69,7 +69,7 @@ class GlancesPlugin(object):
Load the limits from the configuration file
"""
if (hasattr(config, 'has_section') and
config.has_section(self.plugin_name)):
config.has_section(self.plugin_name)):
# print "Load limits for %s" % self.plugin_name
for s, v in config.items(self.plugin_name):
# Read limits
@ -112,21 +112,21 @@ class GlancesPlugin(object):
# Manage limits
ret = 'OK'
if (value > self.get_limit_critical(header=header)):
if value > self.get_limit_critical(header=header):
ret = 'CRITICAL'
elif (value > self.get_limit_warning(header=header)):
elif value > self.get_limit_warning(header=header):
ret = 'WARNING'
elif (value > self.get_limit_careful(header=header)):
elif value > self.get_limit_careful(header=header):
ret = 'CAREFUL'
# Manage log (if needed)
log_str = ""
if (log):
if log:
# Add _LOG to the return string
# So stats will be highlited with a specific color
log_str = "_LOG"
# Get the stat_name = plugin_name (+ header)
if (header == ""):
if header == "":
stat_name = self.plugin_name
else:
stat_name = self.plugin_name + '_' + header
@ -140,13 +140,13 @@ class GlancesPlugin(object):
return self.get_alert(current, min, max, header, log=True)
def get_limit_critical(self, header=""):
if (header == ""):
if header == "":
return self.limits[self.plugin_name + '_' + 'critical']
else:
return self.limits[self.plugin_name + '_' + header + '_' + 'critical']
def get_limit_warning(self, header=""):
if (header == ""):
if header == "":
return self.limits[self.plugin_name + '_' + 'warning']
else:
return self.limits[self.plugin_name + '_' + header + '_' + 'warning']
@ -155,7 +155,7 @@ class GlancesPlugin(object):
"""
Return the hide configuration list key for the current plugin
"""
if (header == ""):
if header == "":
try:
return self.limits[self.plugin_name + '_' + 'hide']
except Exception:
@ -173,7 +173,7 @@ class GlancesPlugin(object):
return value in self.get_hide(header=header)
def get_limit_careful(self, header=""):
if (header == ""):
if header == "":
return self.limits[self.plugin_name + '_' + 'careful']
else:
return self.limits[self.plugin_name + '_' + header + '_' + 'careful']
@ -197,11 +197,11 @@ class GlancesPlugin(object):
column_curse = -1
line_curse = -1
if (hasattr(self, 'display_curse')):
if hasattr(self, 'display_curse'):
display_curse = self.display_curse
if (hasattr(self, 'column_curse')):
if hasattr(self, 'column_curse'):
column_curse = self.column_curse
if (hasattr(self, 'line_curse')):
if hasattr(self, 'line_curse'):
line_curse = self.line_curse
return {'display': display_curse,

View File

@ -65,15 +65,15 @@ class Plugin(GlancesPlugin):
ret = []
# Only process if stats exist and display plugin enable...
# if ((self.stats == {}) or (args.disable_process)):
# if self.stats == {} or args.disable_process:
# return ret
if (args.disable_process):
if args.disable_process:
msg = "{0} ".format(_("PROCESSES DISABLED (press 'z' to display)"))
ret.append(self.curse_add_line(msg))
return ret
if (self.stats == {}):
if self.stats == {}:
return ret
# Build the string message
@ -85,16 +85,16 @@ class Plugin(GlancesPlugin):
msg = "{0}".format(str(self.stats['total']))
ret.append(self.curse_add_line(msg))
if ('thread' in self.stats):
if 'thread' in self.stats:
msg = " ({0} {1}),".format(str(self.stats['thread']), _("thr"))
ret.append(self.curse_add_line(msg))
if ('running' in self.stats):
if 'running' in self.stats:
other -= self.stats['running']
msg = " {0} {1},".format(str(self.stats['running']), _("run"))
ret.append(self.curse_add_line(msg))
if ('sleeping' in self.stats):
if 'sleeping' in self.stats:
other -= self.stats['sleeping']
msg = " {0} {1},".format(str(self.stats['sleeping']), _("slp"))
ret.append(self.curse_add_line(msg))
@ -107,7 +107,7 @@ class Plugin(GlancesPlugin):
args.process_sorted_by
except AttributeError:
args.process_sorted_by = glances_processes.getsortkey()
if (args.process_sorted_by == 'auto'):
if args.process_sorted_by == 'auto':
msg = "{0}".format(_("sorted automatically"))
ret.append(self.curse_add_line(msg))
msg = " {0} {1}".format(_("by"), glances_processes.getsortkey())

View File

@ -67,7 +67,7 @@ class Plugin(GlancesPlugin):
ret = []
# Only process if stats exist and display plugin enable...
if ((self.stats == []) or (args.disable_process)):
if self.stats == [] or args.disable_process:
return ret
# Compute the sort key
@ -75,7 +75,7 @@ class Plugin(GlancesPlugin):
args.process_sorted_by
except AttributeError:
args.process_sorted_by = glances_processes.getsortkey()
if (args.process_sorted_by == 'auto'):
if args.process_sorted_by == 'auto':
process_sort_key = glances_processes.getsortkey()
else:
process_sort_key = args.process_sorted_by
@ -145,7 +145,7 @@ class Plugin(GlancesPlugin):
msg = " {0:>1}".format(p['status'])
ret.append(self.curse_add_line(msg, optional=True))
# TIME+
if (tag_proc_time):
if tag_proc_time:
try:
dtime = timedelta(seconds=sum(p['cpu_times']))
except Exception:
@ -161,17 +161,17 @@ class Plugin(GlancesPlugin):
msg = "{0:>9}".format(msg)
ret.append(self.curse_add_line(msg, optional=True))
# IO read/write
if ('io_counters' in p):
if 'io_counters' in p:
# IO read
io_rs = (p['io_counters'][0] - p['io_counters'][2]) / p['time_since_update']
if (io_rs == 0):
if io_rs == 0:
msg = "{0:>6}".format("0")
else:
msg = "{0:>6}".format(self.auto_unit(io_rs, low_precision=False))
ret.append(self.curse_add_line(msg, optional=True))
# IO write
io_ws = (p['io_counters'][1] - p['io_counters'][3]) / p['time_since_update']
if (io_ws == 0):
if io_ws == 0:
msg = "{0:>6}".format("0")
else:
msg = "{0:>6}".format(self.auto_unit(io_ws, low_precision=False))
@ -194,15 +194,15 @@ class Plugin(GlancesPlugin):
"""
Return the self.stats sorted by sortedby
"""
if (sortedby is None):
if sortedby is None:
# No need to sort...
return self.stats
sortedreverse = True
if (sortedby == 'name'):
if sortedby == 'name':
sortedreverse = False
if (sortedby == 'io_counters'):
if sortedby == 'io_counters':
# Specific case for io_counters
# Sum of io_r + io_w
try:

View File

@ -116,7 +116,7 @@ class Plugin(GlancesPlugin):
ret = []
# Only process if stats exist and display plugin enable...
if ((self.stats == []) or (args.disable_sensors)):
if self.stats == [] or args.disable_sensors:
return ret
# Build the string message

View File

@ -84,12 +84,12 @@ class Plugin(GlancesPlugin):
ret = []
# Build the string message
if (args.client):
if args.client:
# Client mode
if (args.cs_status.lower() == "connected"):
if args.cs_status.lower() == "connected":
msg = _("Connected to ")
ret.append(self.curse_add_line(msg, 'OK'))
elif (args.cs_status.lower() == "disconnected"):
elif args.cs_status.lower() == "disconnected":
msg = _("Disconnected from ")
ret.append(self.curse_add_line(msg, 'CRITICAL'))
@ -97,7 +97,7 @@ class Plugin(GlancesPlugin):
msg = _("{0}").format(self.stats['hostname'])
ret.append(self.curse_add_line(msg, "TITLE"))
# System info
if (self.stats['os_name'] == "Linux"):
if self.stats['os_name'] == "Linux":
msg = _(" ({0} {1} / {2} {3})").format(self.stats['linux_distro'],
self.stats['platform'],
self.stats['os_name'],