Improve PEP8 (S1721)

This commit is contained in:
nicolargo 2015-02-13 22:44:55 +01:00
parent 6b13120503
commit f069d81071
5 changed files with 35 additions and 27 deletions

View File

@ -84,7 +84,7 @@ class GlancesClientBrowser(object):
# Do not retreive stats for statics server # Do not retreive stats for statics server
# Why ? Because for each offline servers, the timeout will be reached # Why ? Because for each offline servers, the timeout will be reached
# So ? The curse interface freezes # So ? The curse interface freezes
if (v['type'] == 'STATIC' and v['status'] in ['UNKNOWN', 'SNMP', 'OFFLINE']): if v['type'] == 'STATIC' and v['status'] in ['UNKNOWN', 'SNMP', 'OFFLINE']:
continue continue
# Select the connection mode (with or without password) # Select the connection mode (with or without password)

View File

@ -195,7 +195,7 @@ class GlancesLogs(object):
""" """
# Create a new clean list # Create a new clean list
clean_logs_list = [] clean_logs_list = []
while (self.len() > 0): while self.len() > 0:
item = self.logs_list.pop() 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) clean_logs_list.insert(0, item)

View File

@ -36,7 +36,8 @@ def is_kernel_thread(proc):
""" Return True if proc is a kernel thread, False instead. """ """ Return True if proc is a kernel thread, False instead. """
try: try:
return os.getpgid(proc.pid) == 0 return os.getpgid(proc.pid) == 0
except OSError: # Python >= 3.3 raises ProcessLookupError, which inherits OSError # Python >= 3.3 raises ProcessLookupError, which inherits OSError
except OSError:
# return False is process is dead # return False is process is dead
return False return False
@ -69,7 +70,8 @@ class ProcessTreeNode(object):
if current_node.is_root: if current_node.is_root:
lines.append(indent_str) lines.append(indent_str)
else: else:
lines.append("%s[%s]" % (indent_str, current_node.process.name())) lines.append("%s[%s]" %
(indent_str, current_node.process.name()))
indent_str = " " * (len(lines[-1]) - 1) indent_str = " " * (len(lines[-1]) - 1)
children_nodes_to_print = collections.deque() children_nodes_to_print = collections.deque()
for child in current_node.children: for child in current_node.children:
@ -77,14 +79,15 @@ class ProcessTreeNode(object):
tree_char = "└─" tree_char = "└─"
else: else:
tree_char = "├─" tree_char = "├─"
children_nodes_to_print.appendleft((indent_str + tree_char, child)) children_nodes_to_print.appendleft(
(indent_str + tree_char, child))
if children_nodes_to_print: if children_nodes_to_print:
nodes_to_print.append(children_nodes_to_print) nodes_to_print.append(children_nodes_to_print)
return "\n".join(lines) return "\n".join(lines)
def set_sorting(self, key, reverse): def set_sorting(self, key, reverse):
""" Set sorting key or func for user with __iter__ (affects the whole tree from this node). """ """ Set sorting key or func for user with __iter__ (affects the whole tree from this node). """
if (self.sort_key != key) or (self.reverse_sorting != reverse): if self.sort_key != key or self.reverse_sorting != reverse:
nodes_to_flag_unsorted = collections.deque([self]) nodes_to_flag_unsorted = collections.deque([self])
while nodes_to_flag_unsorted: while nodes_to_flag_unsorted:
current_node = nodes_to_flag_unsorted.pop() current_node = nodes_to_flag_unsorted.pop()
@ -134,7 +137,8 @@ class ProcessTreeNode(object):
if not self.children_sorted: if not self.children_sorted:
# optimization to avoid sorting twice (once when limiting the maximum processes to grab stats for, # optimization to avoid sorting twice (once when limiting the maximum processes to grab stats for,
# and once before displaying) # and once before displaying)
self.children.sort(key=self.__class__.get_weight, reverse=self.reverse_sorting) self.children.sort(
key=self.__class__.get_weight, reverse=self.reverse_sorting)
self.children_sorted = True self.children_sorted = True
for child in self.children: for child in self.children:
for n in iter(child): for n in iter(child):
@ -151,10 +155,11 @@ class ProcessTreeNode(object):
if not self.children_sorted: if not self.children_sorted:
# optimization to avoid sorting twice (once when limiting the maximum processes to grab stats for, # optimization to avoid sorting twice (once when limiting the maximum processes to grab stats for,
# and once before displaying) # and once before displaying)
self.children.sort(key=self.__class__.get_weight, reverse=self.reverse_sorting) self.children.sort(
key=self.__class__.get_weight, reverse=self.reverse_sorting)
self.children_sorted = True self.children_sorted = True
for child in self.children: for child in self.children:
if (not exclude_incomplete_stats) or ("time_since_update" in child.stats): if not exclude_incomplete_stats or "time_since_update" in child.stats:
yield child yield child
def find_process(self, process): def find_process(self, process):
@ -162,7 +167,7 @@ class ProcessTreeNode(object):
nodes_to_search = collections.deque([self]) nodes_to_search = collections.deque([self])
while nodes_to_search: while nodes_to_search:
current_node = nodes_to_search.pop() current_node = nodes_to_search.pop()
if (not current_node.is_root) and (current_node.process.pid == process.pid): if not current_node.is_root and current_node.process.pid == process.pid:
return current_node return current_node
nodes_to_search.extend(current_node.children) nodes_to_search.extend(current_node.children)
@ -192,13 +197,16 @@ class ProcessTreeNode(object):
# parent is not in tree, add this node later # parent is not in tree, add this node later
nodes_to_add_last.append(new_node) nodes_to_add_last.append(new_node)
# next pass(es): add nodes to their parents if it could not be done in previous pass # next pass(es): add nodes to their parents if it could not be done in
# previous pass
while nodes_to_add_last: while nodes_to_add_last:
node_to_add = nodes_to_add_last.popleft() # pop from left and append to right to avoid infinite loop # pop from left and append to right to avoid infinite loop
node_to_add = nodes_to_add_last.popleft()
try: try:
parent_process = node_to_add.process.parent() parent_process = node_to_add.process.parent()
except psutil.NoSuchProcess: except psutil.NoSuchProcess:
# parent is dead, consider no parent, add this node at the top level # parent is dead, consider no parent, add this node at the top
# level
tree_root.children.append(node_to_add) tree_root.children.append(node_to_add)
else: else:
if parent_process is None: if parent_process is None:
@ -300,9 +308,11 @@ class GlancesProcesses(object):
if value is not None: if value is not None:
try: try:
self.process_filter_re = re.compile(value) self.process_filter_re = re.compile(value)
logger.debug("Process filter regex compilation OK: {0}".format(self.get_process_filter())) logger.debug(
"Process filter regex compilation OK: {0}".format(self.get_process_filter()))
except Exception: except Exception:
logger.error("Cannot compile process filter regex: {0}".format(value)) logger.error(
"Cannot compile process filter regex: {0}".format(value))
self.process_filter_re = None self.process_filter_re = None
else: else:
self.process_filter_re = None self.process_filter_re = None
@ -545,8 +555,7 @@ class GlancesProcesses(object):
processdict = {} processdict = {}
for proc in psutil.process_iter(): for proc in psutil.process_iter():
# Ignore kernel threads if needed # Ignore kernel threads if needed
if (self.no_kernel_threads and (not is_windows) if self.no_kernel_threads and not is_windows and is_kernel_thread(proc):
and is_kernel_thread(proc)):
continue continue
# If self.get_max_processes() is None: Only retreive mandatory stats # If self.get_max_processes() is None: Only retreive mandatory stats
@ -562,10 +571,8 @@ class GlancesProcesses(object):
# ignore the 'idle' process on Windows and *BSD # ignore the 'idle' process on Windows and *BSD
# ignore the 'kernel_task' process on OS X # ignore the 'kernel_task' process on OS X
# waiting for upstream patch from psutil # waiting for upstream patch from psutil
if (is_bsd and processdict[proc]['name'] == 'idle' or if is_bsd and processdict[proc]['name'] == 'idle' or is_windows and processdict[proc]['name'] == 'System Idle Process' or is_mac and processdict[proc]['name'] == 'kernel_task':
is_windows and processdict[proc]['name'] == 'System Idle Process' or continue
is_mac and processdict[proc]['name'] == 'kernel_task'):
continue
# Update processcount (global statistics) # Update processcount (global statistics)
try: try:
self.processcount[str(proc.status())] += 1 self.processcount[str(proc.status())] += 1
@ -592,7 +599,7 @@ class GlancesProcesses(object):
for i, node in enumerate(self.process_tree): for i, node in enumerate(self.process_tree):
# Only retreive stats for visible processes (get_max_processes) # Only retreive stats for visible processes (get_max_processes)
if (self.get_max_processes() is not None) and (i >= self.get_max_processes()): if self.get_max_processes() is not None and i >= self.get_max_processes():
break break
# add standard stats # add standard stats
@ -616,7 +623,8 @@ class GlancesProcesses(object):
processiter = sorted( processiter = sorted(
processdict.items(), key=lambda x: x[1][self.getsortkey()], reverse=True) processdict.items(), key=lambda x: x[1][self.getsortkey()], reverse=True)
except (KeyError, TypeError) as e: except (KeyError, TypeError) as e:
logger.error("Cannot sort process list by %s (%s)" % (self.getsortkey(), e)) logger.error(
"Cannot sort process list by %s (%s)" % (self.getsortkey(), e))
logger.error("%s" % str(processdict.items()[0])) logger.error("%s" % str(processdict.items()[0]))
# Fallback to all process (issue #423) # Fallback to all process (issue #423)
processloop = processdict.items() processloop = processdict.items()

View File

@ -34,7 +34,7 @@ class GlancesWebServer(object):
# Init stats # Init stats
self.stats = GlancesStats(config) self.stats = GlancesStats(config)
if (not is_windows) and args.no_kernel_threads: if not is_windows and args.no_kernel_threads:
# Ignore kernel threads in process list # Ignore kernel threads in process list
glances_processes.disable_kernel_threads() glances_processes.disable_kernel_threads()

View File

@ -77,13 +77,13 @@ class Plugin(GlancesPlugin):
""" Get curses data to display for a process tree. """ """ Get curses data to display for a process tree. """
ret = [] ret = []
node_count = 0 node_count = 0
if (not node.is_root) and ((max_node_count is None) or (max_node_count > 0)): if not node.is_root and ((max_node_count is None) or (max_node_count > 0)):
node_data = self.get_process_curses_data(node.stats, False, args) node_data = self.get_process_curses_data(node.stats, False, args)
node_count += 1 node_count += 1
ret.extend(node_data) ret.extend(node_data)
for child in node.iter_children(): for child in node.iter_children():
# stop if we have enough nodes to display # stop if we have enough nodes to display
if (max_node_count is not None) and (node_count >= max_node_count): if max_node_count is not None and node_count >= max_node_count:
break break
if max_node_count is None: if max_node_count is None:
@ -109,7 +109,7 @@ class Plugin(GlancesPlugin):
# find process command indices in messages # find process command indices in messages
pos = [] pos = []
for i, m in enumerate(child_data): for i, m in enumerate(child_data):
if (m["msg"] == "\n") and (m is not child_data[-1]): if m["msg"] == "\n" and m is not child_data[-1]:
# new line pos + 12 # new line pos + 12
# TODO find a way to get rid of hardcoded 12 value # TODO find a way to get rid of hardcoded 12 value
pos.append(i + 12) pos.append(i + 12)