Issues (46)

glances/exports/glances_json.py (1 issue)

1
"""JSON interface class."""
2
3
import sys
4
5
from glances.globals import json_dumps
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.last_exported_list()[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(listkeys(self.buffer), self.json_filename))
54
55
            # Export stats to JSON file
56
            if PY3:
57
                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...
58
                    self.json_file.write("{}\n".format(json_dumps(self.buffer)))
59
            else:
60
                with open(self.json_filename, "wb") as self.json_file:
61
                    self.json_file.write("{}\n".format(json_dumps(self.buffer)))
62
63
            # Reset buffer
64
            self.buffer = {}
65
66
        # Add current stat to the buffer
67
        self.buffer[name] = dict(zip(columns, points))
68