1 | # |
||
2 | # This file is part of Glances. |
||
3 | # |
||
4 | # SPDX-FileCopyrightText: 2024 Nicolas Hennion <[email protected]> |
||
5 | # |
||
6 | # SPDX-License-Identifier: LGPL-3.0-only |
||
7 | # |
||
8 | |||
9 | """Stdout interface class.""" |
||
10 | |||
11 | import time |
||
12 | |||
13 | from glances.globals import printandflush |
||
14 | from glances.logger import logger |
||
15 | |||
16 | |||
17 | class GlancesStdout: |
||
18 | """This class manages the Stdout display.""" |
||
19 | |||
20 | def __init__(self, config=None, args=None): |
||
21 | # Init |
||
22 | self.config = config |
||
23 | self.args = args |
||
24 | |||
25 | # Build the list of plugin and/or plugin.attribute to display |
||
26 | self.plugins_list = self.build_list() |
||
27 | |||
28 | def build_list(self): |
||
29 | """Return a list of tuples taken from self.args.stdout |
||
30 | |||
31 | :return: A list of tuples. Example [(plugin, key, attribute), ... ] |
||
32 | """ |
||
33 | ret = [] |
||
34 | for p in self.args.stdout.split(','): |
||
35 | pka = p.split('.') |
||
36 | if len(pka) == 1: |
||
37 | # Only plugin name is provided |
||
38 | new = (pka[0], None, None) |
||
39 | elif len(pka) == 2: |
||
40 | # Plugin name and attribute is provided |
||
41 | new = (pka[0], None, pka[1]) |
||
42 | elif len(pka) == 3: |
||
43 | # Plugin name, key and attribute are provided |
||
44 | new = (pka[0], pka[1], pka[2]) |
||
45 | ret.append(new) |
||
0 ignored issues
–
show
introduced
by
Loading history...
|
|||
46 | return ret |
||
47 | |||
48 | def end(self): |
||
49 | pass |
||
50 | |||
51 | def update(self, stats, duration=3): |
||
52 | """Display stats to stdout. |
||
53 | |||
54 | Refresh every duration second. |
||
55 | """ |
||
56 | for plugin, key, attribute in self.plugins_list: |
||
57 | # Check if the plugin exist and is enable |
||
58 | if plugin in stats.getPluginsList() and stats.get_plugin(plugin).is_enabled(): |
||
59 | stat = stats.get_plugin(plugin).get_export() |
||
60 | else: |
||
61 | continue |
||
62 | # Display stats |
||
63 | if attribute is not None: |
||
64 | # With attribute |
||
65 | if isinstance(stat, dict): |
||
66 | try: |
||
67 | printandflush(f"{plugin}.{attribute}: {stat[attribute]}") |
||
68 | except KeyError as err: |
||
69 | logger.error(f"Can not display stat {plugin}.{attribute} ({err})") |
||
70 | elif isinstance(stat, list): |
||
71 | for i in stat: |
||
72 | if key is None: |
||
73 | i_key = i[i['key']] |
||
74 | elif str(key) == str(i[i['key']]): |
||
75 | i_key = key |
||
76 | else: |
||
77 | continue |
||
78 | try: |
||
79 | printandflush(f"{plugin}.{i_key}.{attribute}: {i[attribute]}") |
||
80 | except KeyError as err: |
||
81 | logger.error(f"Can not display stat {plugin}.{attribute} ({err})") |
||
82 | else: |
||
83 | # Without attribute |
||
84 | printandflush(f"{plugin}: {stat}") |
||
85 | |||
86 | # Wait until next refresh |
||
87 | if duration > 0: |
||
88 | time.sleep(duration) |
||
89 |