Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to get battery status data in Python

abhilash

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. True indicates power cabled is plugged. False indicates power cabled is not plugged.

Method signature

psutil.sensors_battery()

Return type

It returns a tuple.

Parameters

The method has no parameters.

Code

import psutil

battery_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,))
Using sensors_battery() method

Explanation

  • Line 1: We import the psutil module.
  • Line 3: We retrieve information about the status of the battery using the sensors_battery() method and store it in battery_status.
  • Lines 4–6: We print percent, secsleft, and power_plugged to the console.

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring