diff --git a/glances/__init__.py b/glances/__init__.py index de85e674..8f268d88 100644 --- a/glances/__init__.py +++ b/glances/__init__.py @@ -22,6 +22,7 @@ # Note: others Glances libs will be imported optionnaly from .core.glances_main import GlancesMain + def main(argv=None): # Create the Glances main instance core = GlancesMain() @@ -47,8 +48,8 @@ def main(argv=None): from .core.glances_client import GlancesClient # Init the client - client = GlancesClient(args=core.get_args(), - server_address=core.server_ip, server_port=int(core.server_port), + client = GlancesClient(args=core.get_args(), + server_address=core.server_ip, server_port=int(core.server_port), username=core.username, password=core.password) # Test if client and server are in the same major version @@ -72,8 +73,8 @@ def main(argv=None): from .core.glances_server import GlancesServer # Init the server - server = GlancesServer(bind_address=core.bind_ip, - bind_port=int(core.server_port), + server = GlancesServer(bind_address=core.bind_ip, + bind_port=int(core.server_port), cached_time=core.cached_time, config=core.get_config()) # print(_("Glances server is running on %s:%s with config file %s") % (core.bind_ip, core.server_port, core.config.get_config_path())) diff --git a/glances/core/glances_client.py b/glances/core/glances_client.py index 4a22d450..454b12ed 100644 --- a/glances/core/glances_client.py +++ b/glances/core/glances_client.py @@ -44,7 +44,7 @@ class GlancesClient(): This class creates and manages the TCP client """ - def __init__(self, + def __init__(self, args=None, server_address="localhost", server_port=61209, username="glances", password=""): @@ -67,7 +67,6 @@ class GlancesClient(): # Init screen self.screen = glancesCurses(args=args) - def login(self): try: client_version = self.client.init() @@ -84,7 +83,6 @@ class GlancesClient(): # print "Server version: {}\nClient version: {}\n".format(__version__, client_version) return __version__[:3] == client_version[:3] - # def client_get_limits(self): # try: # serverlimits = json.loads(self.client.getAllLimits()) @@ -93,7 +91,6 @@ class GlancesClient(): # else: # return serverlimits - # def client_get_monitored(self): # try: # servermonitored = json.loads(self.client.getAllMonitored()) @@ -102,7 +99,6 @@ class GlancesClient(): # else: # return servermonitored - def update(self): # Get stats from server try: @@ -113,7 +109,6 @@ class GlancesClient(): # Put it in the internal dict self.stats.update(server_stats) - def serve_forever(self): while True: # Update the stats diff --git a/glances/core/glances_standalone.py b/glances/core/glances_standalone.py index 6e819a0b..8b1050f0 100644 --- a/glances/core/glances_standalone.py +++ b/glances/core/glances_standalone.py @@ -18,26 +18,17 @@ # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see . -# Import system libs -import sys -import socket -import json - # Import Glances libs -from ..core.glances_limits import glancesLimits from ..core.glances_stats import GlancesStats from ..outputs.glances_curses import glancesCurses + class GlancesStandalone(): """ This class creates and manages the Glances standalone session """ - def __init__(self, - config=None, - args=None, - refresh_time=3, - use_bold=True): + def __init__(self, config=None, args=None, refresh_time=3, use_bold=True): # Init stats self.stats = GlancesStats(config) @@ -64,7 +55,6 @@ class GlancesStandalone(): # Init screen self.screen = glancesCurses(args=args) - def serve_forever(self): while True: # Update system informations @@ -81,4 +71,4 @@ class GlancesStandalone(): # Update the CSV output # !!! TODO # if csv_tag: - # csvoutput.update(stats) \ No newline at end of file + # csvoutput.update(stats) diff --git a/glances/core/glances_stats.py b/glances/core/glances_stats.py index fda3e25c..cfa9373b 100644 --- a/glances/core/glances_stats.py +++ b/glances/core/glances_stats.py @@ -19,8 +19,8 @@ # along with this program. If not, see . # Import system libs -import sys import os +import sys import collections # Import Glances libs @@ -35,7 +35,6 @@ class GlancesStats(object): # Internal dictionnary with all plugins instances _plugins = {} - def __init__(self, config=None): """ Init the stats @@ -47,14 +46,13 @@ class GlancesStats(object): # Load the limits self.load_limits(config) - def __getattr__(self, item): """ - Overwrite the getattr in case of attribute is not found + Overwrite the getattr in case of attribute is not found The goal is to dynamicaly generate the following methods: - getPlugname(): return Plugname stat in JSON format """ - + # Check if the attribute starts with 'get' if (item.startswith('get')): # Get the plugin name @@ -71,13 +69,12 @@ class GlancesStats(object): # Default behavior raise AttributeError(item) - def load_plugins(self): """ Load all plugins in the "plugins" folder """ - plug_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../plugins") + plug_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "../plugins") sys.path.insert(0, plug_dir) header = "glances_" @@ -93,7 +90,6 @@ class GlancesStats(object): plugname = os.path.basename(plug)[len(header):-3].lower() self._plugins[plugname] = m.Plugin() - def load_limits(self, config): """ Load the stats limits @@ -103,7 +99,6 @@ class GlancesStats(object): for p in self._plugins: self._plugins[p].load_limits(config) - def __update__(self, input_stats): """ Update the stats @@ -123,18 +118,15 @@ class GlancesStats(object): # print "Plugins: %s" % self._plugins self._plugins[p].set(input_stats[p]) - def update(self, input_stats={}): # !!! Why __update__ and update method ? # Update the stats self.__update__(input_stats) - def get_plugin_list(self): # Return the plugin list self._plugins - def get_plugin(self, plugin_name): # Return the plugin name if (plugin_name in self._plugins): @@ -153,19 +145,17 @@ class GlancesStatsServer(GlancesStats): # all_stats is a dict of dicts filled by the server self.all_stats = collections.defaultdict(dict) - - def update(self, input_stats = {}): + def update(self, input_stats={}): """ Update the stats """ - + # Update the stats GlancesStats.__update__(self, input_stats) # Build the all_stats with the get_raw() method of the plugins for p in self._plugins: self.all_stats[p] = self._plugins[p].get_raw() - def getAll(self): return self.all_stats @@ -182,19 +172,17 @@ class GlancesStatsClient(GlancesStats): # all_stats is a dict of dicts filled by the server self.all_stats = collections.defaultdict(dict) - - def update(self, input_stats = {}): + def update(self, input_stats={}): """ Update the stats """ - + # Update the stats GlancesStats.__update__(self, input_stats) # Build the all_stats with the get_raw() method of the plugins for p in self._plugins: self.all_stats[p] = self._plugins[p].get_raw() - def getAll(self): return self.all_stats diff --git a/glances/outputs/glances_curses.py b/glances/outputs/glances_curses.py index 6f8778a5..f546bec3 100644 --- a/glances/outputs/glances_curses.py +++ b/glances/outputs/glances_curses.py @@ -148,7 +148,6 @@ class glancesCurses: self.term_window.nodelay(1) self.pressedkey = -1 - def __getkey(self, window): """ A getKey function to catch ESC key AND Numlock key (issue #163) @@ -163,7 +162,6 @@ class glancesCurses: else: return keycode[0] - def __catchKey(self): # Get key #~ self.pressedkey = self.term_window.getch() @@ -235,7 +233,6 @@ class glancesCurses: # Return the key code return self.pressedkey - def end(self): # Shutdown the curses window curses.echo() @@ -243,7 +240,6 @@ class glancesCurses: curses.curs_set(1) curses.endwin() - def display(self, stats, cs_status="None"): """ Display stats on the screen @@ -262,7 +258,7 @@ class glancesCurses: screen_x = self.screen.getmaxyx()[1] screen_y = self.screen.getmaxyx()[0] - # Update the client server status + # Update the client server status self.args.cs_status = cs_status # Display first line (system+uptime) @@ -271,7 +267,7 @@ class glancesCurses: l = self.get_curse_width(stats_system) + self.get_curse_width(stats_uptime) + self.space_between_column self.display_plugin(stats_system, display_optional=(screen_x >= l)) self.display_plugin(stats_uptime) - + # Display second line (CPU|PERCPU+LOAD+MEM+SWAP+) # CPU|PERCPU if (self.args.percpu): @@ -318,10 +314,7 @@ class glancesCurses: self.display_plugin(stats_processlist, max_y=(screen_y - self.get_curse_height(stats_alert) - 3)) self.display_plugin(stats_alert) - - def display_plugin(self, plugin_stats, - display_optional=True, - max_y=65535): + def display_plugin(self, plugin_stats, display_optional=True, max_y=65535): """ Display the plugin_stats on the screen If display_optional=True display the optional stats @@ -373,9 +366,9 @@ class glancesCurses: # Is it possible to display the stat with the current screen size # !!! Crach if not try/except... Why ??? try: - self.term_window.addnstr(y, x, - m['msg'], - screen_x - x, # Do not disply outside the screen + self.term_window.addnstr(y, x, + m['msg'], + screen_x - x, # Do not disply outside the screen self.__colors_list[m['decoration']]) except: pass @@ -385,16 +378,14 @@ class glancesCurses: # Compute the next Glances column/line position if (plugin_stats['column'] > -1): - self.column_to_x[plugin_stats['column'] + 1] = x + self.space_between_column + self.column_to_x[plugin_stats['column'] + 1] = x + self.space_between_column if (plugin_stats['line'] > -1): self.line_to_y[plugin_stats['line'] + 1] = y + self.space_between_line - def erase(self): # Erase the content of the screen self.term_window.erase() - def flush(self, stats, cs_status="None"): """ Clear and update screen @@ -407,7 +398,6 @@ class glancesCurses: self.erase() self.display(stats, cs_status=cs_status) - def update(self, stats, cs_status="None"): """ Update the screen and wait __refresh_time sec / catch key every 100 ms @@ -430,32 +420,30 @@ class glancesCurses: # Wait 100ms... curses.napms(100) - def get_curse_width(self, curse_msg, without_option=False): # Return the width of the formated curses message - # The height is defined by the maximum line + # The height is defined by the maximum line try: if (without_option): # Size without options - c = len(max(''.join([ (i['msg'] if not i['optional'] else "") - for i in curse_msg['msgdict'] ]).split('\n'), key=len)) + c = len(max(''.join([(i['msg'] if not i['optional'] else "") + for i in curse_msg['msgdict']]).split('\n'), key=len)) else: # Size with all options - c = len(max(''.join([ i['msg'] - for i in curse_msg['msgdict'] ]).split('\n'), key=len)) + c = len(max(''.join([i['msg'] + for i in curse_msg['msgdict']]).split('\n'), key=len)) except: return 0 else: return c - def get_curse_height(self, curse_msg): # Return the height of the formated curses message # The height is defined by the number of '\n' try: - c = [ i['msg'] for i in curse_msg['msgdict']].count('\n') + c = [i['msg'] for i in curse_msg['msgdict']].count('\n') except: return 0 else: diff --git a/glances/plugins/glances_plugin.py b/glances/plugins/glances_plugin.py index d416c778..bc1fbc27 100644 --- a/glances/plugins/glances_plugin.py +++ b/glances/plugins/glances_plugin.py @@ -1,250 +1,250 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# -# Glances - An eye on your system -# -# Copyright (C) 2014 Nicolargo -# -# Glances is free software; you can redistribute it and/or modify -# it under the terms of the GNU Lesser General Public License as published by -# the Free Software Foundation, either version 3 of the License, or -# (at your option) any later version. -# -# Glances is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU Lesser General Public License for more details. -# -# You should have received a copy of the GNU Lesser General Public License -# along with this program. If not, see . - -# Import system libs -import json - -# Import Glances lib -from glances.core.glances_globals import glances_logs - - -class GlancesPlugin(object): - """ - Main class for Glances' plugin - """ - - def __init__(self): - # Plugin name (= module name without glances_) - self.plugin_name = self.__class__.__module__[len('glances_'):] - - # Init the stats list - self.stats = None - - # Init the limits dictionnary - self.limits = dict() - - def load_limits(self, config): - """ - Load the limits from the configuration file - """ - if (hasattr(config, 'has_section') and - config.has_section(self.plugin_name)): - # print "Load limits for %s" % self.plugin_name - for s, v in config.items(self.plugin_name): - # Read limits - # print "\t%s = %s" % (self.plugin_name + '_' + s, v) - self.limits[self.plugin_name + '_' + s] = config.get_option(self.plugin_name, s) - - def __repr__(self): - # Return the raw stats - return self.stats - - def __str__(self): - # Return the human-readable stats - return str(self.stats) - - def get_raw(self): - # Return the stats object - return self.stats - - def get_stats(self): - # Return the stats object in JSON format for the RPC API - return json.dumps(self.stats) - - def get_limits(self): - # Return the limits object - return self.limits - - def get_alert(self, current=0, min=0, max=100, header="", log=False): - # Return the alert status relative to a current value - # Use this function for minor stat - # If current < CAREFUL of max then alert = OK - # If current > CAREFUL of max then alert = CAREFUL - # If current > WARNING of max then alert = WARNING - # If current > CRITICAL of max then alert = CRITICAL - # stat is USER, SYSTEM, IOWAIT or STEAL - # - # If defined 'header' is added between the plugin name and the status - # Only usefull for stats with several alert status - # - # If log=True than return the logged status - - # Compute the % - try: - value = (current * 100) / max - except ZeroDivisionError: - return 'DEFAULT' - except TypeError: - return 'DEFAULT' - - # Manage limits - ret = 'OK' - if (value > self.get_limit_critical(header=header)): - ret = 'CRITICAL' - elif (value > self.get_limit_warning(header=header)): - ret = 'WARNING' - elif (value > self.get_limit_careful(header=header)): - ret = 'CAREFUL' - - # Manage log (if needed) - log_str = "" - if (log): - # Add _LOG to the return string - # So stats will be highlited with a specific color - log_str = "_LOG" - # Get the stat_name = plugin_name (+ header) - if (header == ""): - stat_name = self.plugin_name - else: - stat_name = self.plugin_name + '_' + header - # !!! TODO: Manage the process list (last param => []) - glances_logs.add(ret, stat_name.upper(), value, []) - - # Default is ok - return ret + log_str - - def get_alert_log(self, current=0, min=0, max=100, header=""): - return self.get_alert(current, min, max, header, log=True) - - def get_limit_critical(self, header=""): - if (header == ""): - return self.limits[self.plugin_name + '_' + 'critical'] - else: - return self.limits[self.plugin_name + '_' + header + '_' + 'critical'] - - def get_limit_warning(self, header=""): - if (header == ""): - return self.limits[self.plugin_name + '_' + 'warning'] - else: - return self.limits[self.plugin_name + '_' + header + '_' + 'warning'] - - def get_limit_careful(self, header=""): - if (header == ""): - return self.limits[self.plugin_name + '_' + 'careful'] - else: - return self.limits[self.plugin_name + '_' + header + '_' + 'careful'] - - def msg_curse(self, args): - """ - Return default string to display in the curse interface - """ - return [self.curse_add_line(str(self.stats))] - - def get_curse(self, args=None): - # Return a dict with all the information needed to display the stat - # key | description - #---------------------------- - # display | Display the stat (True or False) - # msgdict | Message to display (list of dict [{ 'msg': msg, 'decoration': decoration } ... ]) - # column | column number - # line | Line number - - display_curse = False - column_curse = -1 - line_curse = -1 - - if (hasattr(self, 'display_curse')): - display_curse = self.display_curse - if (hasattr(self, 'column_curse')): - column_curse = self.column_curse - if (hasattr(self, 'line_curse')): - line_curse = self.line_curse - - return {'display': display_curse, - 'msgdict': self.msg_curse(args), - 'column': column_curse, - 'line': line_curse} - - def curse_add_line(self, msg, decoration="DEFAULT", optional=False): - """ - Return a dict with: { 'msg': msg, 'decoration': decoration, 'optional': False } - with: - msg: string - decoration: - DEFAULT: no decoration - UNDERLINE: underline - BOLD: bold - TITLE: for stat title - OK: Value is OK and non logged - OK_LOG: Value is OK and logged - CAREFUL: Value is CAREFUL and non logged - CAREFUL_LOG: Value is CAREFUL and logged - WARNING: Value is WARINING and non logged - WARNING_LOG: Value is WARINING and logged - CRITICAL: Value is CRITICAL and non logged - CRITICAL_LOG: Value is CRITICAL and logged - optional: True if the stat is optional (display only if space is available) - """ - - return {'msg': msg, 'decoration': decoration, 'optional': optional} - - def curse_new_line(self): - """ - Go to a new line - """ - return self.curse_add_line('\n') - - def auto_unit(self, val, low_precision=False): - """ - Make a nice human readable string out of val - Number of decimal places increases as quantity approaches 1 - - examples: - CASE: 613421788 RESULT: 585M low_precision: 585M - CASE: 5307033647 RESULT: 4.94G low_precision: 4.9G - CASE: 44968414685 RESULT: 41.9G low_precision: 41.9G - CASE: 838471403472 RESULT: 781G low_precision: 781G - CASE: 9683209690677 RESULT: 8.81T low_precision: 8.8T - CASE: 1073741824 RESULT: 1024M low_precision: 1024M - CASE: 1181116006 RESULT: 1.10G low_precision: 1.1G - - parameter 'low_precision=True' returns less decimal places. - potentially sacrificing precision for more readability - """ - symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') - prefix = { - 'Y': 1208925819614629174706176, - 'Z': 1180591620717411303424, - 'E': 1152921504606846976, - 'P': 1125899906842624, - 'T': 1099511627776, - 'G': 1073741824, - 'M': 1048576, - 'K': 1024 - } - - for key in reversed(symbols): - value = float(val) / prefix[key] - if value > 1: - fixed_decimal_places = 0 - if value < 10: - fixed_decimal_places = 2 - elif value < 100: - fixed_decimal_places = 1 - if low_precision: - if key in 'MK': - fixed_decimal_places = 0 - else: - fixed_decimal_places = min(1, fixed_decimal_places) - elif key in 'K': - fixed_decimal_places = 0 - formatter = "{0:.%df}{1}" % fixed_decimal_places - return formatter.format(value, key) - return "{0!s}".format(val) +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# +# Glances - An eye on your system +# +# Copyright (C) 2014 Nicolargo +# +# Glances is free software; you can redistribute it and/or modify +# it under the terms of the GNU Lesser General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# Glances is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Lesser General Public License for more details. +# +# You should have received a copy of the GNU Lesser General Public License +# along with this program. If not, see . + +# Import system libs +import json + +# Import Glances lib +from glances.core.glances_globals import glances_logs + + +class GlancesPlugin(object): + """ + Main class for Glances' plugin + """ + + def __init__(self): + # Plugin name (= module name without glances_) + self.plugin_name = self.__class__.__module__[len('glances_'):] + + # Init the stats list + self.stats = None + + # Init the limits dictionnary + self.limits = dict() + + def load_limits(self, config): + """ + Load the limits from the configuration file + """ + if (hasattr(config, 'has_section') and + config.has_section(self.plugin_name)): + # print "Load limits for %s" % self.plugin_name + for s, v in config.items(self.plugin_name): + # Read limits + # print "\t%s = %s" % (self.plugin_name + '_' + s, v) + self.limits[self.plugin_name + '_' + s] = config.get_option(self.plugin_name, s) + + def __repr__(self): + # Return the raw stats + return self.stats + + def __str__(self): + # Return the human-readable stats + return str(self.stats) + + def get_raw(self): + # Return the stats object + return self.stats + + def get_stats(self): + # Return the stats object in JSON format for the RPC API + return json.dumps(self.stats) + + def get_limits(self): + # Return the limits object + return self.limits + + def get_alert(self, current=0, min=0, max=100, header="", log=False): + # Return the alert status relative to a current value + # Use this function for minor stat + # If current < CAREFUL of max then alert = OK + # If current > CAREFUL of max then alert = CAREFUL + # If current > WARNING of max then alert = WARNING + # If current > CRITICAL of max then alert = CRITICAL + # stat is USER, SYSTEM, IOWAIT or STEAL + # + # If defined 'header' is added between the plugin name and the status + # Only usefull for stats with several alert status + # + # If log=True than return the logged status + + # Compute the % + try: + value = (current * 100) / max + except ZeroDivisionError: + return 'DEFAULT' + except TypeError: + return 'DEFAULT' + + # Manage limits + ret = 'OK' + if (value > self.get_limit_critical(header=header)): + ret = 'CRITICAL' + elif (value > self.get_limit_warning(header=header)): + ret = 'WARNING' + elif (value > self.get_limit_careful(header=header)): + ret = 'CAREFUL' + + # Manage log (if needed) + log_str = "" + if (log): + # Add _LOG to the return string + # So stats will be highlited with a specific color + log_str = "_LOG" + # Get the stat_name = plugin_name (+ header) + if (header == ""): + stat_name = self.plugin_name + else: + stat_name = self.plugin_name + '_' + header + # !!! TODO: Manage the process list (last param => []) + glances_logs.add(ret, stat_name.upper(), value, []) + + # Default is ok + return ret + log_str + + def get_alert_log(self, current=0, min=0, max=100, header=""): + return self.get_alert(current, min, max, header, log=True) + + def get_limit_critical(self, header=""): + if (header == ""): + return self.limits[self.plugin_name + '_' + 'critical'] + else: + return self.limits[self.plugin_name + '_' + header + '_' + 'critical'] + + def get_limit_warning(self, header=""): + if (header == ""): + return self.limits[self.plugin_name + '_' + 'warning'] + else: + return self.limits[self.plugin_name + '_' + header + '_' + 'warning'] + + def get_limit_careful(self, header=""): + if (header == ""): + return self.limits[self.plugin_name + '_' + 'careful'] + else: + return self.limits[self.plugin_name + '_' + header + '_' + 'careful'] + + def msg_curse(self, args): + """ + Return default string to display in the curse interface + """ + return [self.curse_add_line(str(self.stats))] + + def get_curse(self, args=None): + # Return a dict with all the information needed to display the stat + # key | description + #---------------------------- + # display | Display the stat (True or False) + # msgdict | Message to display (list of dict [{ 'msg': msg, 'decoration': decoration } ... ]) + # column | column number + # line | Line number + + display_curse = False + column_curse = -1 + line_curse = -1 + + if (hasattr(self, 'display_curse')): + display_curse = self.display_curse + if (hasattr(self, 'column_curse')): + column_curse = self.column_curse + if (hasattr(self, 'line_curse')): + line_curse = self.line_curse + + return {'display': display_curse, + 'msgdict': self.msg_curse(args), + 'column': column_curse, + 'line': line_curse} + + def curse_add_line(self, msg, decoration="DEFAULT", optional=False): + """ + Return a dict with: { 'msg': msg, 'decoration': decoration, 'optional': False } + with: + msg: string + decoration: + DEFAULT: no decoration + UNDERLINE: underline + BOLD: bold + TITLE: for stat title + OK: Value is OK and non logged + OK_LOG: Value is OK and logged + CAREFUL: Value is CAREFUL and non logged + CAREFUL_LOG: Value is CAREFUL and logged + WARNING: Value is WARINING and non logged + WARNING_LOG: Value is WARINING and logged + CRITICAL: Value is CRITICAL and non logged + CRITICAL_LOG: Value is CRITICAL and logged + optional: True if the stat is optional (display only if space is available) + """ + + return {'msg': msg, 'decoration': decoration, 'optional': optional} + + def curse_new_line(self): + """ + Go to a new line + """ + return self.curse_add_line('\n') + + def auto_unit(self, val, low_precision=False): + """ + Make a nice human readable string out of val + Number of decimal places increases as quantity approaches 1 + + examples: + CASE: 613421788 RESULT: 585M low_precision: 585M + CASE: 5307033647 RESULT: 4.94G low_precision: 4.9G + CASE: 44968414685 RESULT: 41.9G low_precision: 41.9G + CASE: 838471403472 RESULT: 781G low_precision: 781G + CASE: 9683209690677 RESULT: 8.81T low_precision: 8.8T + CASE: 1073741824 RESULT: 1024M low_precision: 1024M + CASE: 1181116006 RESULT: 1.10G low_precision: 1.1G + + parameter 'low_precision=True' returns less decimal places. + potentially sacrificing precision for more readability + """ + symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y') + prefix = { + 'Y': 1208925819614629174706176, + 'Z': 1180591620717411303424, + 'E': 1152921504606846976, + 'P': 1125899906842624, + 'T': 1099511627776, + 'G': 1073741824, + 'M': 1048576, + 'K': 1024 + } + + for key in reversed(symbols): + value = float(val) / prefix[key] + if value > 1: + fixed_decimal_places = 0 + if value < 10: + fixed_decimal_places = 2 + elif value < 100: + fixed_decimal_places = 1 + if low_precision: + if key in 'MK': + fixed_decimal_places = 0 + else: + fixed_decimal_places = min(1, fixed_decimal_places) + elif key in 'K': + fixed_decimal_places = 0 + formatter = "{0:.%df}{1}" % fixed_decimal_places + return formatter.format(value, key) + return "{0!s}".format(val)