Test Failed
Push — develop ( 66c9ff...e21229 )
by Nicolas
05:06
created

glances/outputs/glances_stdout_csv.py (5 issues)

1
# -*- coding: utf-8 -*-
2
#
3
# This file is part of Glances.
4
#
5
# Copyright (C) 2019 Nicolargo <[email protected]>
6
#
7
# Glances is free software; you can redistribute it and/or modify
8
# it under the terms of the GNU Lesser General Public License as published by
9
# the Free Software Foundation, either version 3 of the License, or
10
# (at your option) any later version.
11
#
12
# Glances is distributed in the hope that it will be useful,
13
# but WITHOUT ANY WARRANTY; without even the implied warranty of
14
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15
# GNU Lesser General Public License for more details.
16
#
17
# You should have received a copy of the GNU Lesser General Public License
18
# along with this program. If not, see <http://www.gnu.org/licenses/>.
19
20
"""StdoutCsv interface class."""
21
22
import time
0 ignored issues
show
import missing from __future__ import absolute_import
Loading history...
23
24
from glances.logger import logger
0 ignored issues
show
import missing from __future__ import absolute_import
Loading history...
Unused logger imported from glances.logger
Loading history...
25
from glances.compat import printandflush
0 ignored issues
show
import missing from __future__ import absolute_import
Loading history...
26
27
28
class GlancesStdoutCsv(object):
29
30
    """
31
    This class manages the StdoutCsv display.
32
    """
33
34
    separator = ','
35
    na = 'N/A'
36
37
    def __init__(self, config=None, args=None):
38
        # Init
39
        self.config = config
40
        self.args = args
41
42
        # Display the header only on the first line
43
        self.header = True
44
45
        # Build the list of plugin and/or plugin.attribute to display
46
        self.plugins_list = self.build_list()
47
48
    def build_list(self):
49
        """Return a list of tuples taken from self.args.stdout
50
        [(plugin, attribute), ... ]"""
51
        ret = []
52
        for p in self.args.stdout_csv.split(','):
53
            if '.' in p:
54
                p, a = p.split('.')
55
            else:
56
                a = None
57
            ret.append((p, a))
58
        return ret
59
60
    def end(self):
61
        pass
62
63
    def build_header(self, plugin, attribute, stat):
64
        """Build and return the header line"""
65
        line = ''
66
67
        if attribute is not None:
68
            line += '{}.{}{}'.format(plugin, attribute, self.separator)
69
        else:
70
            if isinstance(stat, dict):
71
                for k in stat.keys():
72
                    line += '{}.{}{}'.format(plugin,
73
                                             str(k),
74
                                             self.separator)
75
            elif isinstance(stat, list):
76
                for i in stat:
77
                    if isinstance(i, dict) and 'key' in i:
78
                        for k in i.keys():
79
                            line += '{}.{}.{}{}'.format(plugin,
80
                                                        str(i['key']),
81
                                                        str(k),
82
                                                        self.separator)
83
            else:
84
                line += '{}{}'.format(plugin, self.separator)
85
86
        return line
87
88
    def build_data(self, plugin, attribute, stat):
0 ignored issues
show
The argument plugin seems to be unused.
Loading history...
89
        """Build and return the data line"""
90
        line = ''
91
92
        if attribute is not None:
93
            line += '{}{}'.format(str(stat.get(attribute, self.na)),
94
                                  self.separator)
95
        else:
96
            if isinstance(stat, dict):
97
                for v in stat.values():
98
                    line += '{}{}'.format(str(v), self.separator)
99
            elif isinstance(stat, list):
100
                for i in stat:
101
                    if isinstance(i, dict) and 'key' in i:
102
                        for v in i.values():
103
                            line += '{}{}'.format(str(v), self.separator)
104
            else:
105
                line += '{}{}'.format(str(stat), self.separator)
106
107
        return line
108
109
    def update(self,
110
               stats,
111
               duration=3):
112
        """Display stats to stdout.
113
        Refresh every duration second.
114
        """
115
        # Build the stats list
116
        line = ''
117
        for plugin, attribute in self.plugins_list:
118
            # Check if the plugin exist and is enable
119
            if plugin in stats.getPluginsList() and \
120
               stats.get_plugin(plugin).is_enable():
121
                stat = stats.get_plugin(plugin).get_export()
122
            else:
123
                continue
124
125
            # Build the line to display (header or data)
126
            if self.header:
127
                line += self.build_header(plugin, attribute, stat)
128
            else:
129
                line += self.build_data(plugin, attribute, stat)
130
131
        # Display the line (without the last 'separator')
132
        printandflush(line[:-1])
133
134
        # Display header one time
135
        self.header = False
136
137
        # Wait until next refresh
138
        if duration > 0:
139
            time.sleep(duration)
140