Issues (49)

glances/exports/glances_json/__init__.py (1 issue)

1
"""JSON interface class."""
2
3
import sys
4
5
from glances.exports.export import GlancesExport
6
from glances.globals import json_dumps, listkeys
7
from glances.logger import logger
8
9
10
class Export(GlancesExport):
11
    """This class manages the JSON export module."""
12
13
    def __init__(self, config=None, args=None):
14
        """Init the JSON export IF."""
15
        super().__init__(config=config, args=args)
16
17
        # JSON file name
18
        self.json_filename = args.export_json_file
19
20
        # Set the JSON output file
21
        try:
22
            self.json_file = open(self.json_filename, 'w')
23
            self.json_file.close()
24
        except OSError as e:
25
            logger.critical(f"Cannot create the JSON file: {e}")
26
            sys.exit(2)
27
28
        logger.info(f"Exporting stats to file: {self.json_filename}")
29
30
        self.export_enable = True
31
32
        # Buffer for dict of stats
33
        self.buffer = {}
34
35
    def exit(self):
36
        """Close the JSON file."""
37
        logger.debug(f"Finalise export interface {self.export_name}")
38
        self.json_file.close()
39
40
    def export(self, name, columns, points):
41
        """Export the stats to the JSON file."""
42
43
        # Check for completion of loop for all exports
44
        if name == self.last_exported_list()[0] and self.buffer != {}:
45
            # One whole loop has been completed
46
            # Flush stats to file
47
            logger.debug(f"Exporting stats ({listkeys(self.buffer)}) to JSON file ({self.json_filename})")
48
49
            # Export stats to JSON file
50
            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...
51
                self.json_file.write(f"{json_dumps(self.buffer)}\n")
52
53
            # Reset buffer
54
            self.buffer = {}
55
56
        # Add current stat to the buffer
57
        self.buffer[name] = dict(zip(columns, points))
58