chg: ruff - flake-return fixes

This commit is contained in:
Bharath Vignesh J K 2024-05-17 02:31:54 +05:30
parent d392caf6f6
commit b4c2a4c24a
43 changed files with 154 additions and 217 deletions

View File

@ -109,16 +109,14 @@ class GlancesAmp(object):
"""Generic method to get the item in the AMP configuration"""
if key in self.configs:
return self.configs[key]
else:
return None
return None
def enable(self):
"""Return True|False if the AMP is enabled in the configuration file (enable=true|false)."""
ret = self.get('enable')
if ret is None:
return False
else:
return ret.lower().startswith('true')
return ret.lower().startswith('true')
def regex(self):
"""Return regular expression used to identified the current application."""
@ -133,8 +131,7 @@ class GlancesAmp(object):
ret = self.get('one_line')
if ret is None:
return False
else:
return ret.lower().startswith('true')
return ret.lower().startswith('true')
def time_until_refresh(self):
"""Return time in seconds until refresh."""
@ -193,5 +190,4 @@ class GlancesAmp(object):
# Call the children update method
if self.should_update():
return self.update(process_list)
else:
return self.result()
return self.result()

View File

@ -66,8 +66,7 @@ class GlancesAttribute(object):
def value(self):
if self.history_len() > 0:
return (self._value[1] - self.history_value()[1]) / (self._value[0] - self.history_value()[0])
else:
return None
return None
@value.setter
def value(self, new_value):

View File

@ -148,8 +148,7 @@ class GlancesAutoDiscoverServer(object):
"""Return the current server list (dict of dict)."""
if zeroconf_tag and self.zeroconf_enable_tag:
return self.listener.get_servers_list()
else:
return []
return []
def set_server(self, server_pos, key, value):
"""Set the key to the value for the server_pos (position in the list)."""

View File

@ -182,12 +182,12 @@ class GlancesClient(object):
"""Update stats from Glances/SNMP server."""
if self.client_mode == 'glances':
return self.update_glances()
elif self.client_mode == 'snmp':
if self.client_mode == 'snmp':
return self.update_snmp()
else:
self.end()
logger.critical("Unknown server mode: {}".format(self.client_mode))
sys.exit(2)
self.end()
logger.critical("Unknown server mode: {}".format(self.client_mode))
sys.exit(2)
def update_glances(self):
"""Get stats from Glances server.

View File

@ -77,8 +77,7 @@ class GlancesClientBrowser(object):
if clear_password is not None:
server['password'] = self.password.get_hash(clear_password)
return 'http://{}:{}@{}:{}'.format(server['username'], server['password'], server['ip'], server['port'])
else:
return 'http://{}:{}'.format(server['ip'], server['port'])
return 'http://{}:{}'.format(server['ip'], server['port'])
def __update_stats(self, server):
"""Update stats for the given server (picked from the server list)"""

View File

@ -46,8 +46,7 @@ class CpuPercent(object):
If percpu, return the percpu stats"""
if percpu:
return self.__get_percpu()
else:
return self.__get_cpu()
return self.__get_cpu()
def get_info(self):
"""Get additional information about the CPU"""

View File

@ -158,8 +158,7 @@ def build_global_message():
if themax['weight'] >= themax['thresholds_min']:
# Check if the weight is > to the minimal threshold value
return themax['msg']
else:
return tree[0]['msg']
return tree[0]['msg']
class GlancesEventsList(object):

View File

@ -122,8 +122,7 @@ class GlancesExport(object):
logger.error("No 'key' available in {}".format(item))
if isinstance(ret, list):
return ret[0]
else:
return ret
return ret
def parse_tags(self, tags):
"""Parse tags into a dict.

View File

@ -100,6 +100,4 @@ def normalize(name):
"""Normalize name for the Graphite convention"""
# Name should not contain space
ret = name.replace(' ', '_')
return ret
return name.replace(' ', '_')

View File

@ -84,7 +84,7 @@ class Export(GlancesExport):
)
# Create the write client
write_client = client.write_api(
return client.write_api(
write_options=WriteOptions(
batch_size=500,
flush_interval=self.interval * 1000,
@ -95,7 +95,6 @@ class Export(GlancesExport):
exponential_base=2,
)
)
return write_client
def _normalize(self, name, columns, points):
"""Normalize data for the InfluxDB's data model.

View File

@ -67,8 +67,7 @@ class Export(GlancesExport):
self.protocol + '://' + self.user + ':' + self.password + '@' + self.host + ':' + self.port + '/'
)
connection = pika.BlockingConnection(parameters)
channel = connection.channel()
return channel
return connection.channel()
except Exception as e:
logger.critical("Connection to rabbitMQ server %s:%s failed. %s" % (self.host, self.port, e))
sys.exit(2)
@ -79,8 +78,8 @@ class Export(GlancesExport):
for i in range(len(columns)):
if not isinstance(points[i], Number):
continue
else:
data += ", " + columns[i] + "=" + str(points[i])
data += ", " + columns[i] + "=" + str(points[i])
logger.debug(data)
try:
self.client.basic_publish(exchange='', routing_key=self.queue, body=data)

View File

@ -48,8 +48,7 @@ class Export(GlancesExport):
if not self.export_enable:
return None
try:
client = bernhard.Client(host=self.host, port=self.port)
return client
return bernhard.Client(host=self.host, port=self.port)
except Exception as e:
logger.critical("Connection to Riemann failed : %s " % e)
return None
@ -59,10 +58,10 @@ class Export(GlancesExport):
for i in range(len(columns)):
if not isinstance(points[i], Number):
continue
else:
data = {'host': self.hostname, 'service': name + " " + columns[i], 'metric': points[i]}
logger.debug(data)
try:
self.client.send(data)
except Exception as e:
logger.error("Cannot export stats to Riemann (%s)" % e)
data = {'host': self.hostname, 'service': name + " " + columns[i], 'metric': points[i]}
logger.debug(data)
try:
self.client.send(data)
except Exception as e:
logger.error("Cannot export stats to Riemann (%s)" % e)

View File

@ -69,6 +69,4 @@ def normalize(name):
# Name should not contain some specials chars (issue #1068)
ret = name.replace(':', '')
ret = ret.replace('%', '')
ret = ret.replace(' ', '_')
return ret
return ret.replace(' ', '_')

View File

@ -156,9 +156,9 @@ class GlancesFilter(object):
if self.filter_key is None:
# Apply filter on command line and process name
return self._is_process_filtered(process, key='name') or self._is_process_filtered(process, key='cmdline')
else:
# Apply filter on <key>
return self._is_process_filtered(process)
# Apply filter on <key>
return self._is_process_filtered(process)
def _is_process_filtered(self, process, key=None):
"""Return True if the process[key] should be filtered according to the current filter"""

View File

@ -67,8 +67,7 @@ class FolderList(object):
value['path'] = self.config.get_value(section, key + 'path')
if value['path'] is None:
continue
else:
value['path'] = nativestr(value['path'])
value['path'] = nativestr(value['path'])
# Optional conf keys
# Refresh time

View File

@ -128,10 +128,9 @@ def b(s, errors='replace'):
def nativestr(s, errors='replace'):
if isinstance(s, text_type):
return s
elif isinstance(s, (int, float)):
if isinstance(s, (int, float)):
return s.__str__()
else:
return s.decode('utf-8', errors=errors)
return s.decode('utf-8', errors=errors)
def system_exec(command):
@ -331,8 +330,7 @@ def json_dumps_dictlist(data, item):
dl = dictlist(data, item)
if dl is None:
return None
else:
return json_dumps(dl)
return json_dumps(dl)
def string_value_to_float(s):

View File

@ -76,6 +76,7 @@ class Bar(object):
return self.__size
if self.__display_value:
return self.__size - 6
return None
@property
def percent(self):

View File

@ -154,9 +154,9 @@ class _GlancesCurses(object):
logger.info("Cannot init the curses library, quiet mode on and export.")
args.quiet = True
return
else:
logger.critical("Cannot init the curses library ({})".format(e))
sys.exit(1)
logger.critical("Cannot init the curses library ({})".format(e))
sys.exit(1)
# Load configuration file
self.load_config(config)
@ -359,8 +359,7 @@ class _GlancesCurses(object):
def get_key(self, window):
# TODO: Check issue #163
ret = window.getch()
return ret
return window.getch()
def __catch_key(self, return_to_browser=False):
# Catch the pressed key
@ -990,7 +989,8 @@ class _GlancesCurses(object):
popup.refresh()
self.wait(duration * 1000)
return True
elif popup_type == 'input':
if popup_type == 'input':
logger.info(popup_type)
logger.info(is_password)
# Create a sub-window for the text field
@ -1010,17 +1010,17 @@ class _GlancesCurses(object):
self.set_cursor(0)
if textbox != '':
return textbox
else:
return None
else:
textbox = GlancesTextbox(sub_pop, insert_mode=True)
textbox.edit()
self.set_cursor(0)
if textbox.gather() != '':
return textbox.gather()[:-1]
else:
return None
elif popup_type == 'yesno':
return None
# No password
textbox = GlancesTextbox(sub_pop, insert_mode=True)
textbox.edit()
self.set_cursor(0)
if textbox.gather() != '':
return textbox.gather()[:-1]
return None
if popup_type == 'yesno':
# # Create a sub-window for the text field
sub_pop = popup.derwin(1, 2, len(sentence_list) + 1, len(m) + 2)
sub_pop.attron(self.colors_list['FILTER'])
@ -1038,6 +1038,8 @@ class _GlancesCurses(object):
# self.term_window.keypad(0)
return textbox.gather()
return None
def display_plugin(self, plugin_stats, display_optional=True, display_additional=True, max_y=65535, add_space=0):
"""Display the plugin_stats on the screen.
@ -1132,6 +1134,7 @@ class _GlancesCurses(object):
# Have empty lines after the plugins
self.next_line += add_space
return None
def clear(self):
"""Erase the content of the screen.
@ -1214,8 +1217,7 @@ class _GlancesCurses(object):
if isexitkey and self.args.help_tag:
# Quit from help should return to main screen, not exit #1874
self.args.help_tag = not self.args.help_tag
isexitkey = False
return isexitkey
return False
if not isexitkey and pressedkey > -1:
# Redraw display

View File

@ -59,6 +59,7 @@ class Sparkline(object):
return self.__size
if self.__display_value:
return self.__size - 6
return None
@property
def percents(self):

View File

@ -82,8 +82,7 @@ def indent_stat(stat, indent=' '):
if isinstance(stat, list) and len(stat) > 1 and isinstance(stat[0], dict):
# Only display two first items
return indent + pformat(stat[0:2]).replace('\n', '\n' + indent).replace("'", '"')
else:
return indent + pformat(stat).replace('\n', '\n' + indent).replace("'", '"')
return indent + pformat(stat).replace('\n', '\n' + indent).replace("'", '"')
def print_api_status():

View File

@ -25,5 +25,4 @@ def unicode_message(key, args=None):
"""Return the unicode message for the given key."""
if args and hasattr(args, 'disable_unicode') and args.disable_unicode:
return _unicode_message[key][1]
else:
return _unicode_message[key][0]
return _unicode_message[key][0]

View File

@ -38,8 +38,7 @@ class GlancesPassword(object):
"""
if self.config is None:
return user_config_dir()[0]
else:
return self.config.get_value('passwords', 'local_password_path', default=user_config_dir()[0])
return self.config.get_value('passwords', 'local_password_path', default=user_config_dir()[0])
@weak_lru_cache(maxsize=32)
def get_hash(self, plain_password, salt=''):
@ -120,6 +119,4 @@ class GlancesPassword(object):
"""Load the hashed password from the Glances folder."""
# Read the password file, if it exists
with open(self.password_file, 'r') as file_pwd:
hashed_password = file_pwd.read()
return hashed_password
return file_pwd.read()

View File

@ -51,14 +51,14 @@ class GlancesPasswordList(GlancesPassword):
"""
if host is None:
return self._password_dict
else:
try:
return self._password_dict[host]
except (KeyError, TypeError):
try:
return self._password_dict[host]
return self._password_dict['default']
except (KeyError, TypeError):
try:
return self._password_dict['default']
except (KeyError, TypeError):
return None
return None
def set_password(self, host, password):
"""Set a password for a specific host."""

View File

@ -183,5 +183,4 @@ class PluginModel(GlancesPluginModel):
"""Compare a with b using the tolerance (if numerical)."""
if str(int(a)).isdigit() and str(int(b)).isdigit():
return abs(a - b) <= max(abs(a), abs(b)) * tolerance
else:
return a == b
return a == b

View File

@ -93,13 +93,11 @@ class PluginModel(GlancesPluginModel):
if nbprocess > 0:
if int(countmin) <= int(nbprocess) <= int(countmax):
return 'OK'
else:
return 'WARNING'
else:
if int(countmin) == 0:
return 'OK'
else:
return 'CRITICAL'
return 'WARNING'
if int(countmin) == 0:
return 'OK'
return 'CRITICAL'
def msg_curse(self, args=None, max_width=None):
"""Return the dict to display in the curse interface."""

View File

@ -164,8 +164,7 @@ class PluginModel(GlancesPluginModel):
conf_podman_sock = self.get_conf_value('podman_sock')
if len(conf_podman_sock) == 0:
return "unix:///run/user/1000/podman/podman.sock"
else:
return conf_podman_sock[0]
return conf_podman_sock[0]
def exit(self):
"""Overwrite the exit method to close threads."""
@ -209,8 +208,7 @@ class PluginModel(GlancesPluginModel):
all_tag = self.get_conf_value('all')
if len(all_tag) == 0:
return False
else:
return all_tag[0].lower() == 'true'
return all_tag[0].lower() == 'true'
@GlancesPluginModel._check_decorator
@GlancesPluginModel._log_result_decorator
@ -453,12 +451,11 @@ class PluginModel(GlancesPluginModel):
"""Analyse the container status."""
if status == 'running':
return 'OK'
elif status == 'exited':
if status == 'exited':
return 'WARNING'
elif status == 'dead':
if status == 'dead':
return 'CRITICAL'
else:
return 'CAREFUL'
return 'CAREFUL'
def sort_docker_stats(stats):

View File

@ -71,13 +71,12 @@ class DockerStatsFetcher:
memory_stats = self._get_memory_stats()
network_stats = self._get_network_stats()
computed_stats = {
return {
"io": io_stats or {},
"memory": memory_stats or {},
"network": network_stats or {},
"cpu": cpu_stats or {"total": 0.0},
}
return computed_stats
@property
def time_since_update(self):

View File

@ -216,8 +216,7 @@ class PluginModel(GlancesPluginModel):
# Do not take hidden file system into account
if self.is_hide(fs_current['mnt_point']):
continue
else:
stats.append(fs_current)
stats.append(fs_current)
else:
# Default behavior
for fs in fs_stat:
@ -232,8 +231,7 @@ class PluginModel(GlancesPluginModel):
# Do not take hidden file system into account
if self.is_hide(fs_current['mnt_point']) or self.is_hide(fs_current['device_name']):
continue
else:
stats.append(fs_current)
stats.append(fs_current)
# Update the stats
self.stats = stats

View File

@ -37,6 +37,7 @@ See: https://wiki.archlinux.org/title/AMDGPU#Manually
import os
import re
from typing import Optional
DRM_ROOT_FOLDER: str = '/sys/class/drm'
CARD_REGEX: str = r"^card\d$"
@ -104,7 +105,7 @@ def get_device_name(device_folder: str) -> str:
return 'AMD GPU'
def get_mem(device_folder: str) -> int:
def get_mem(device_folder: str) -> Optional[int]:
"""Return the memory consumption in %."""
mem_info_vram_total = os.path.join(device_folder, GPU_MEM_TOTAL)
mem_info_vram_used = os.path.join(device_folder, GPU_MEM_USED)
@ -118,7 +119,7 @@ def get_mem(device_folder: str) -> int:
return None
def get_proc(device_folder: str) -> int:
def get_proc(device_folder: str) -> Optional[int]:
"""Return the processor consumption in %."""
gpu_busy_percent = os.path.join(device_folder, GPU_PROC_PERCENT)
if os.path.isfile(gpu_busy_percent):
@ -127,7 +128,7 @@ def get_proc(device_folder: str) -> int:
return None
def get_temperature(device_folder: str) -> int:
def get_temperature(device_folder: str) -> Optional[int]:
"""Return the processor temperature in °C (mean of all HWMON)"""
temp_input = []
for root, dirs, _ in os.walk(device_folder):
@ -140,10 +141,9 @@ def get_temperature(device_folder: str) -> int:
temp_input.append(int(f.read()))
if len(temp_input) > 0:
return round(sum(temp_input) / len(temp_input) / 1000)
else:
return None
return None
def get_fan_speed(device_folder: str) -> int:
def get_fan_speed(device_folder: str) -> Optional[int]:
"""Return the fan speed in %."""
return None

View File

@ -111,8 +111,7 @@ class PluginModel(GlancesPluginModel):
stats = self.get_stats_snmp(snmp_oid=snmp_oid)
if stats['min1'] == '':
stats = self.get_init_value()
return stats
return self.get_init_value()
# Python 3 return a dict like:
# {'min1': "b'0.08'", 'min5': "b'0.12'", 'min15': "b'0.15'"}
@ -206,5 +205,4 @@ def get_load_average(percent: bool = False):
if load_average and percent:
return tuple([round(i / get_nb_log_core() * 100, 1) for i in load_average])
else:
return load_average
return load_average

View File

@ -151,7 +151,7 @@ class GlancesPluginModel(object):
def get_key(self):
"""Return the key of the list."""
return None
return
def is_enabled(self, plugin_name=None):
"""Return true if plugin is enabled."""
@ -227,11 +227,9 @@ class GlancesPluginModel(object):
s = self.stats_history.get(nb=nb)
if item is None:
return s
else:
if item in s:
return s[item]
else:
return None
if item in s:
return s[item]
return None
def get_export_history(self, item=None):
"""Return the stats history object to export."""
@ -410,14 +408,14 @@ class GlancesPluginModel(object):
"""
if not isinstance(self.get_raw(), list):
return None
else:
if (not isinstance(value, int) and not isinstance(value, float)) and value.isdigit():
value = int(value)
try:
return {value: [i for i in self.get_raw() if i[item] == value]}
except (KeyError, ValueError) as e:
logger.error("Cannot get item({})=value({}) ({})".format(item, value, e))
return None
if (not isinstance(value, int) and not isinstance(value, float)) and value.isdigit():
value = int(value)
try:
return {value: [i for i in self.get_raw() if i[item] == value]}
except (KeyError, ValueError) as e:
logger.error("Cannot get item({})=value({}) ({})".format(item, value, e))
return None
def get_stats_value(self, item, value):
"""Return the stats object for a specific item=value in JSON format.
@ -427,15 +425,13 @@ class GlancesPluginModel(object):
rsv = self.get_raw_stats_value(item, value)
if rsv is None:
return None
else:
return json_dumps(rsv)
return json_dumps(rsv)
def get_item_info(self, item, key, default=None):
"""Return the item info grabbed into self.fields_description."""
if self.fields_description is None or item not in self.fields_description:
return default
else:
return self.fields_description[item].get(key, default)
return self.fields_description[item].get(key, default)
def update_views_hidden(self):
"""Update the hidden views
@ -553,14 +549,11 @@ class GlancesPluginModel(object):
if key is None:
return item_views
else:
if option is None:
return item_views[key]
else:
if option in item_views[key]:
return item_views[key][option]
else:
return 'DEFAULT'
if option is None:
return item_views[key]
if option in item_views[key]:
return item_views[key][option]
return 'DEFAULT'
def get_json_views(self, item=None, key=None, option=None):
"""Return the views (in JSON)."""
@ -626,8 +619,7 @@ class GlancesPluginModel(object):
"""Return the limits object."""
if item is None:
return self._limits
else:
return self._limits.get('{}_{}'.format(self.plugin_name, item), None)
return self._limits.get('{}_{}'.format(self.plugin_name, item), None)
def get_stats_action(self):
"""Return stats for the action.
@ -742,12 +734,11 @@ class GlancesPluginModel(object):
"""Filter the stats to keep only the fields we want (the one defined in fields_description)."""
if hasattr(stats, '_asdict'):
return {k: v for k, v in stats._asdict().items() if k in self.fields_description}
elif isinstance(stats, dict):
if isinstance(stats, dict):
return {k: v for k, v in stats.items() if k in self.fields_description}
elif isinstance(stats, list):
if isinstance(stats, list):
return [self.filter_stats(s) for s in stats]
else:
return stats
return stats
def manage_threshold(self, stat_name, trigger):
"""Manage the threshold for the current stat."""
@ -793,8 +784,7 @@ class GlancesPluginModel(object):
"""Return true if the criticality limit exist for the given stat_name"""
if stat_name == "":
return self.plugin_name + '_' + criticality in self._limits
else:
return stat_name + '_' + criticality in self._limits
return stat_name + '_' + criticality in self._limits
def get_limit(self, criticality=None, stat_name=""):
"""Return the limit value for the given criticality.
@ -806,7 +796,7 @@ class GlancesPluginModel(object):
# Example: network_wlan0_rx_careful
if stat_name + '_' + criticality in self._limits:
return self._limits[stat_name + '_' + criticality]
elif self.plugin_name + '_' + criticality in self._limits:
if self.plugin_name + '_' + criticality in self._limits:
return self._limits[self.plugin_name + '_' + criticality]
# No key found, the raise an error
@ -840,10 +830,9 @@ class GlancesPluginModel(object):
# Example: network_wlan0_rx_log
if stat_name + '_log' in self._limits:
return self._limits[stat_name + '_log'][0].lower() == 'true'
elif self.plugin_name + '_log' in self._limits:
if self.plugin_name + '_log' in self._limits:
return self._limits[self.plugin_name + '_log'][0].lower() == 'true'
else:
return default_action
return default_action
def get_conf_value(self, value, header="", plugin_name=None, default=[]):
"""Return the configuration (header_) value for the current plugin.
@ -895,14 +884,12 @@ class GlancesPluginModel(object):
"""Return True if the value should be displayed in the UI"""
if self.get_conf_value('show', header=header) != []:
return self.is_show(value, header=header)
else:
return not self.is_hide(value, header=header)
return not self.is_hide(value, header=header)
def read_alias(self):
if self.plugin_name + '_' + 'alias' in self._limits:
return {i.split(':')[0].lower(): i.split(':')[1] for i in self._limits[self.plugin_name + '_' + 'alias']}
else:
return dict()
return dict()
def has_alias(self, header):
"""Return the alias name for the relative header it it exists otherwise None."""

View File

@ -313,8 +313,7 @@ class ThreadScanner(threading.Thread):
"""Scan the port structure (dict) and update the status key."""
if int(port['port']) == 0:
return self._port_scan_icmp(port)
else:
return self._port_scan_tcp(port)
return self._port_scan_tcp(port)
def _resolv_name(self, hostname):
"""Convert hostname to IP address."""

View File

@ -835,8 +835,7 @@ class PluginModel(GlancesPluginModel):
"""Return the decoration string for the current mmm status."""
if mmm is not None:
return 'DEFAULT'
else:
return 'FILTER'
return 'FILTER'
def __mmm_reset(self):
"""Reset the MMM stats."""
@ -902,6 +901,6 @@ class PluginModel(GlancesPluginModel):
"""Return the maximum PID size in number of char."""
if self.pid_max is not None:
return len(str(self.pid_max))
else:
# By default return 5 (corresponding to 99999 PID number)
return 5
# By default return 5 (corresponding to 99999 PID number)
return 5

View File

@ -161,6 +161,6 @@ class PluginModel(GlancesPluginModel):
return 'CRITICAL'
if used is None or available is None:
return 'DEFAULT'
elif used < available:
if used < available:
return 'WARNING'
return 'OK'

View File

@ -153,8 +153,7 @@ class PluginModel(GlancesPluginModel):
# Remove duplicates thanks to https://stackoverflow.com/a/9427216/1919431
stats_transformed = [dict(t) for t in {tuple(d.items()) for d in stats_transformed}]
# Sort by label
stats_transformed = sorted(stats_transformed, key=lambda d: d['label'])
return stats_transformed
return sorted(stats_transformed, key=lambda d: d['label'])
@GlancesPluginModel._check_decorator
@GlancesPluginModel._log_result_decorator
@ -191,10 +190,9 @@ class PluginModel(GlancesPluginModel):
# Get the alias for each stat
if self.has_alias(stats["label"].lower()):
return self.has_alias(stats["label"].lower())
elif self.has_alias("{}_{}".format(stats["label"], stats["type"]).lower()):
if self.has_alias("{}_{}".format(stats["label"], stats["type"]).lower()):
return self.has_alias("{}_{}".format(stats["label"], stats["type"]).lower())
else:
return stats["label"]
return stats["label"]
def __set_type(self, stats, sensor_type):
"""Set the plugin type.
@ -254,9 +252,9 @@ class PluginModel(GlancesPluginModel):
return ''
if stats['status'].startswith('Charg'):
return unicode_message('ARROW_UP')
elif stats['status'].startswith('Discharg'):
if stats['status'].startswith('Discharg'):
return unicode_message('ARROW_DOWN')
elif stats['status'].startswith('Full'):
if stats['status'].startswith('Full'):
return unicode_message('CHECK')
return ''

View File

@ -83,6 +83,4 @@ class PluginModel(GlancesPluginModel):
if not self.stats or self.is_disabled():
return ret
ret = [self.curse_add_line('Uptime: {}'.format(self.stats))]
return ret
return [self.curse_add_line('Uptime: {}'.format(self.stats))]

View File

@ -568,8 +568,7 @@ class GlancesProcesses(object):
If as_programs is True, return the list of programs."""
if as_programs:
return processes_to_programs(self.processlist)
else:
return self.processlist
return self.processlist
def get_export(self):
"""Return the processlist for export."""

View File

@ -40,7 +40,7 @@ def __secure_popen(cmd):
cmd_split_redirect = cmd.split('>')
if len(cmd_split_redirect) > 2:
return 'Glances error: Only one file redirection allowed ({})'.format(cmd)
elif len(cmd_split_redirect) == 2:
if len(cmd_split_redirect) == 2:
stdout_redirect = cmd_split_redirect[1].strip()
cmd = cmd_split_redirect[0]
else:

View File

@ -68,17 +68,15 @@ class GlancesXMLRPCHandler(SimpleXMLRPCRequestHandler, object):
# TODO: config is not taken into account: it may be a problem ?
pwd = GlancesPassword(username=username, config=None)
return pwd.check_password(self.server.user_dict[username], password)
else:
return False
return False
def parse_request(self):
if SimpleXMLRPCRequestHandler.parse_request(self):
# Next we authenticate
if self.authenticate(self.headers):
return True
else:
# if authentication fails, tell the client
self.send_error(401, 'Authentication failed')
# if authentication fails, tell the client
self.send_error(401, 'Authentication failed')
return False
def log_message(self, log_format, *args):

View File

@ -55,10 +55,9 @@ class GlancesStats(object):
if hasattr(plugin, 'get_json_views'):
# The method get_views exist, return it
return getattr(plugin, 'get_json_views')
else:
# The method get_views is not found for the plugin
raise AttributeError(item)
elif item.startswith('get'):
# The method get_views is not found for the plugin
raise AttributeError(item)
if item.startswith('get'):
# Get the plugin name
plugname = item[len('get') :].lower()
# Get the plugin instance
@ -66,12 +65,10 @@ class GlancesStats(object):
if hasattr(plugin, 'get_stats'):
# The method get_stats exist, return it
return getattr(plugin, 'get_stats')
else:
# The method get_stats is not found for the plugin
raise AttributeError(item)
else:
# Default behavior
# The method get_stats is not found for the plugin
raise AttributeError(item)
# Default behavior
raise AttributeError(item)
def load_modules(self, args):
"""Wrapper to load: plugins and export modules."""
@ -237,8 +234,7 @@ class GlancesStats(object):
"""
if enable:
return [p for p in self._plugins if self._plugins[p].is_enabled()]
else:
return [p for p in self._plugins]
return [p for p in self._plugins]
def getExportsList(self, enable=True):
"""Return the exports list.
@ -250,8 +246,7 @@ class GlancesStats(object):
"""
if enable:
return [e for e in self._exports]
else:
return [e for e in self._exports_all]
return [e for e in self._exports_all]
def load_limits(self, config=None):
"""Load the stats limits (except the one in the exclude list)."""
@ -367,8 +362,7 @@ class GlancesStats(object):
"""Return the plugin name."""
if plugin_name in self._plugins:
return self._plugins[plugin_name]
else:
return None
return None
def end(self):
"""End of the Glances stats."""

View File

@ -38,18 +38,17 @@ class GlancesThresholds(object):
if stat_name in self._thresholds:
return self._thresholds[stat_name]
else:
return {}
return {}
def add(self, stat_name, threshold_description):
"""Add a new threshold to the dict (key = stat_name)"""
if threshold_description not in self.threshold_list:
return False
else:
self._thresholds[stat_name] = getattr(
self.current_module, 'GlancesThreshold' + threshold_description.capitalize()
)()
return True
self._thresholds[stat_name] = getattr(
self.current_module, 'GlancesThreshold' + threshold_description.capitalize()
)()
return True
# Global variable uses to share thresholds between Glances components

View File

@ -21,7 +21,7 @@ select = [
"W", # pycodestyle
# "UP", # pyupgrde
# "C4", # flake8-comprehensions
# "RET", # flake8-return
"RET", # flake8-return
# "FBT", # flake8-boolean-trap
# "RUF", # Ruff-specific rules
# "PERF", # Perflint

View File

@ -31,7 +31,7 @@ with open('README.rst', encoding='utf-8') as f:
def get_data_files():
data_files = [
return [
(
'share/doc/glances',
['AUTHORS', 'COPYING', 'NEWS.rst', 'README.rst', "SECURITY.md", 'CONTRIBUTING.md', 'conf/glances.conf'],
@ -39,8 +39,6 @@ def get_data_files():
('share/man/man1', ['docs/man/glances.1']),
]
return data_files
with open('requirements.txt') as f:
required = f.read().splitlines()