Find Battery Percentage and Charging status in Windows and Linux using Python

Hey Coder! In this article, we are going to get the Battery percentage using Python.

In this Program, we will be needing the psutil Library to get the information of the Battery.

Let us know more about psutil Library and the required methods for finding battery percentage before getting into the program.

psutil

The psutil is the shorthand notation for the python system and process utilities.

The psutil Library used to get information about the ongoing processes and system utilization like information about CPU, memory, etc in Python.

As psutil Library is not built-in, we have to install it before we use it.

We can install psutil using the following command in the command prompt.

pip install psutil

We are going to use the method sensors_battery() defined in psutil Library to get the information about the Battery.

syntax: psutil.sensors_battery()

The method sensors_battery() returns the battery status information in the form of a named tuple. The battery status information includes:

percent: It is the percentage of battery left.

secsleft: It is the capacity of the battery in seconds.

power_plugged:  It indicates the status of charging of the battery. It is True if the battery is charging and False if the battery is discharging.

The value of power_plugged is assigned to None if the battery status cannot be determined.

The method psutil.sensors_battery() returns None if the battery is not found.

Program

Let us first import the psutil Library.

import psutil

Now, let us get the named tuple with battery information using the method psutil.sensors_battery().

Store the battery information in the variable battery_info.

battery_info = psutil.sensors_battery()

Now, we can get the battery percentage using battery_info.percentage and print the value.

Similarly, we can know the charging status using battery_info.power_plugged.

We are going to print that the battery is charging if the battery_info.power_plugged is True and print that the battery is discharging if it is False.

print("Battery Percentage : ",battery_info.percent)
if battery_info.power_plugged == True :
    print("The Battery is Charging")
elif battery_info.power_plugged == False:
    print("The Battery is Discharging")

OUTPUT

Battery Percentage : 60
The Battery is Discharging

Yahoo! We have successfully retrieved the battery information using Python.

Thank You for reading the article. I hope this article helped you some way. Also do check out our other articles below:

 

Leave a Reply

Your email address will not be published.