Test Failed
Push — master ( aea994...69b639 )
by Nicolas
03:44 queued 10s
created

glances.exports.glances_json.Export.export()   B

Complexity

Conditions 6

Size

Total Lines 25
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 12
nop 4
dl 0
loc 25
rs 8.6666
c 0
b 0
f 0
1
"""JSON interface class."""
2
3
import sys
4
import json
5
6
from glances.compat import PY3, listkeys
7
from glances.logger import logger
8
from glances.exports.glances_export import GlancesExport
9
10
11
class Export(GlancesExport):
12
13
    """This class manages the JSON export module."""
14
15
    def __init__(self, config=None, args=None):
16
        """Init the JSON export IF."""
17
        super(Export, self).__init__(config=config, args=args)
18
19
        # JSON file name
20
        self.json_filename = args.export_json_file
21
22
        # Set the JSON output file
23
        try:
24
            if PY3:
25
                self.json_file = open(self.json_filename, 'w')
26
                self.json_file.close()
27
            else:
28
                self.json_file = open(self.json_filename, 'wb')
29
                self.json_file.close()
30
        except IOError as e:
31
            logger.critical("Cannot create the JSON file: {}".format(e))
32
            sys.exit(2)
33
34
        logger.info("Exporting stats to file: {}".format(self.json_filename))
35
36
        self.export_enable = True
37
38
        # Buffer for dict of stats
39
        self.buffer = {}
40
41
    def exit(self):
42
        """Close the JSON file."""
43
        logger.debug("Finalise export interface %s" % self.export_name)
44
        self.json_file.close()
45
46
    def export(self, name, columns, points):
47
        """Export the stats to the JSON file."""
48
49
        # Check for completion of loop for all exports
50
        if name == self.plugins_to_export()[0] and self.buffer != {}:
51
            # One whole loop has been completed
52
            # Flush stats to file
53
            logger.debug("Exporting stats ({}) to JSON file ({})".format(
54
                listkeys(self.buffer),
55
                self.json_filename)
56
            )
57
58
            # Export stats to JSON file
59
            if PY3:
60
                with open(self.json_filename, "w") as self.json_file:
0 ignored issues
show
Comprehensibility Best Practice introduced by
The variable self does not seem to be defined.
Loading history...
61
                    self.json_file.write("{}\n".format(json.dumps(self.buffer)))
62
            else:
63
                with open(self.json_filename, "wb") as self.json_file:
64
                    self.json_file.write("{}\n".format(json.dumps(self.buffer)))
65
66
            # Reset buffer
67
            self.buffer = {}
68
69
        # Add current stat to the buffer
70
        self.buffer[name] = dict(zip(columns, points))
71