Get Laptop Battery Percentage using Python

Hello, Internet programmers let’s do a code in python to show laptop battery percentage. Let’s jump to the code.

We are gonna use psutil python module to do this task. psutil (process and system utilities) is a cross-platform library for retrieving information on running processes and system utilization (CPU, memory, disks, network, sensors) in Python.

It is useful mainly for system monitoring, profiling and limiting process resources and management of running processes. It implements many functionalities offered by classic UNIX command line tools such as ps, top, iotop, lsof, netstat, ifconfig, free and others. psutil currently supports the following platforms:

  • Linux
  • Windows
  • macOS
  • FreeBSD, OpenBSD, NetBSD
  • Sun Solaris
  • AIX

Installation

Open your terminal and type the following command and it starts downloading

pip install psutil

Install psutil in Linux

sudo apt-get install gcc python3-dev

sudo pip3 install psutil

Code

# python script showing battery details
import psutil
  
# function returning time in hh:mm:ss
def convertTime(seconds):
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return "%d:%02d:%02d" % (hours, minutes, seconds)
  
# returns a tuple
battery = psutil.sensors_battery()
  
print("Battery percentage : ", battery.percent)
print("Power plugged in : ", battery.power_plugged)
  
# converting seconds to hh:mm:ss
print("Battery left : ", convertTime(battery.secsleft))

Output

Get Laptop Battery Percentage using Python, Python script to shows Laptop Battery Percentage

psutil.sensors.battery() returns a named tuple consisting of the following values. If no battery is installed or metrics can’t be determined None is returned.

  • percent: Power left in percentage.
  • secsleft: Approx seconds left before the power runs out. It is set to psutil.POWER_TIME_UNLIMITED if it is on charging. If this value can’t be determined it is set to psutil.POWER_TIME_UNKNOWN .
  • power_plugged: True if power is plugged in, False if it isn’t charging or None if it can’t be determined.

Happy Coding 🙂

You may also like,

Support CodeSnail

If you appreciate my work, or if it has helped you along your journey. It would mean a lot to me if you could write a message on my wall and share a cup of coffee (or tea) with me.

Buy Me A Coffee

Related Articles

Your subscription could not be saved. Please try again.
Your subscription has been successful.

Newsletter

Subscribe to our newsletter and stay updated.

Leave a Comment

Copy link
Powered by Social Snap