How to get battery status data in Python
What is the psutil module?
The psutil (Python system and process utilities) module is a Python package that retrieves information on ongoing processes and system usage (CPU, memory, storage, network, and sensors). It is mostly used for system monitoring, profiling, restricting process resources, and process management.
The module can be installed via pip as follows:
pip install psutil
The sensors_battery method
The sensors_battery method is used to return the battery status information with the following attributes:
percent: The percentage of battery/power left in the system.secsleft: A rough approximation of how long the battery will last. This value is in seconds.power_plugged: This is a boolean value indicating whether the power cable is plugged or not.Trueindicates power cabled is plugged.Falseindicates power cabled is not plugged.
Method signature
psutil.sensors_battery()
Return type
It returns a tuple.
Parameters
The method has no parameters.
Code
import psutilbattery_status = psutil.sensors_battery()print(battery_status)print("Percentage of battery: %s %" % (battery_status.percent,))print("Approx time remaining: %s seconds" % (battery_status.secsleft,))print("Is power cable connected: %s" % (battery_status.power_plugged,))
Explanation
- Line 1: We import the
psutilmodule. - Line 3: We retrieve information about the status of the battery using the
sensors_battery()method and store it inbattery_status. - Lines 4–6: We print
percent,secsleft, andpower_pluggedto the console.