From 13adb3b781319ba7f4cf446aab5603656ebbc5fa Mon Sep 17 00:00:00 2001 From: nicolargo Date: Tue, 7 Mar 2017 18:57:37 +0100 Subject: [PATCH] Use psutil.sensors_battery() as a backup of batinfo --- glances/plugins/glances_batpercent.py | 42 ++++++++++++++++++++------- 1 file changed, 32 insertions(+), 10 deletions(-) diff --git a/glances/plugins/glances_batpercent.py b/glances/plugins/glances_batpercent.py index 4febe72b..dcc6bd51 100644 --- a/glances/plugins/glances_batpercent.py +++ b/glances/plugins/glances_batpercent.py @@ -19,14 +19,26 @@ """Battery plugin.""" +import psutil + from glances.logger import logger from glances.plugins.glances_plugin import GlancesPlugin # Batinfo library (optional; Linux-only) +batinfo_tag = True try: import batinfo except ImportError: - logger.debug("Batinfo library not found. Glances cannot grab battery info.") + logger.debug("batpercent plugin - Batinfo library not found. Trying fallback to PsUtil.") + batinfo_tag = False + +# PsUtil library 5.2.0 or higher (optional; Linux-only) +psutil_tag = True +try: + psutil.sensors_battery() +except AttributeError: + logger.debug("batpercent plugin - PsUtil 5.2.0 or higher is needed to grab battery stats.") + psutil_tag = False class Plugin(GlancesPlugin): @@ -80,24 +92,34 @@ class GlancesGrabBat(object): def __init__(self): """Init batteries stats.""" - try: + self.bat_list = [] + + if batinfo_tag: self.bat = batinfo.batteries() - self.initok = True - self.bat_list = [] - self.update() - except Exception as e: - self.initok = False - logger.debug("Cannot init GlancesGrabBat class (%s)" % e) + elif psutil_tag: + self.bat = psutil + else: + self.bat = None def update(self): """Update the stats.""" - if self.initok: + if batinfo_tag: + # Use the batinfo lib to grab the stats + # Compatible with multiple batteries self.bat.update() self.bat_list = [{ 'label': 'Battery', 'value': self.battery_percent, 'unit': '%'}] + elif psutil_tag: + # Use the PSUtil 5.2.0 or higher lib to grab the stats + # Give directly the battery percent + self.bat_list = [{ + 'label': 'Battery', + 'value': int(self.bat.sensors_battery().percent), + 'unit': '%'}] else: + # No stats... self.bat_list = [] def get(self): @@ -107,7 +129,7 @@ class GlancesGrabBat(object): @property def battery_percent(self): """Get batteries capacity percent.""" - if not self.initok or not self.bat.stat: + if not batinfo_tag or not self.bat.stat: return [] # Init the bsum (sum of percent)