Python script to shows Laptop Battery Percentage

Monitoring your laptop's battery percentage is essential for uninterrupted usage. Python provides a simple way to create scripts that display battery information using the psutil library. This tutorial shows how to create a Python script that retrieves and displays your laptop's current battery percentage.

Prerequisites

Before creating the script, ensure you have the following requirements ?

  • Python Python 3.6 or higher installed on your system

  • psutil Library Install using pip with the following command ?

pip install psutil

The psutil library works across Windows, macOS, and Linux systems, making our script cross-platform compatible.

Basic Battery Information Script

Let's start with a simple script to display the battery percentage ?

import psutil

def get_battery_info():
    battery = psutil.sensors_battery()
    
    if battery is None:
        print("No battery found on this device.")
        return None
    
    percentage = battery.percent
    power_plugged = battery.power_plugged
    
    print(f"Battery Percentage: {percentage}%")
    print(f"Power Adapter: {'Plugged In' if power_plugged else 'Not Plugged'}")
    
    return battery

get_battery_info()
Battery Percentage: 85%
Power Adapter: Not Plugged

Enhanced Battery Monitor with Time Remaining

This enhanced version includes estimated time remaining and charging status ?

import psutil
import datetime

def detailed_battery_info():
    battery = psutil.sensors_battery()
    
    if battery is None:
        print("No battery detected on this system.")
        return
    
    percentage = battery.percent
    power_plugged = battery.power_plugged
    time_left = battery.secsleft
    
    print(f"Battery Status Report")
    print(f"{'='*25}")
    print(f"Charge Level: {percentage}%")
    print(f"Power Adapter: {'Connected' if power_plugged else 'Disconnected'}")
    
    if time_left != psutil.POWER_TIME_UNLIMITED:
        hours, remainder = divmod(time_left, 3600)
        minutes, _ = divmod(remainder, 60)
        if power_plugged:
            print(f"Time to Full Charge: {hours}h {minutes}m")
        else:
            print(f"Time Remaining: {hours}h {minutes}m")
    else:
        print("Time Remaining: Calculating...")
    
    print(f"Timestamp: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")

detailed_battery_info()
Battery Status Report
=========================
Charge Level: 72%
Power Adapter: Disconnected
Time Remaining: 3h 45m
Timestamp: 2024-01-15 14:30:22

Continuous Battery Monitoring

Create a script that monitors battery status continuously with customizable refresh intervals ?

import psutil
import time
import os

def monitor_battery(refresh_interval=60, low_battery_threshold=20):
    """
    Monitor battery status continuously
    refresh_interval: seconds between updates
    low_battery_threshold: percentage to trigger warning
    """
    try:
        while True:
            os.system('cls' if os.name == 'nt' else 'clear')  # Clear screen
            
            battery = psutil.sensors_battery()
            
            if battery is None:
                print("No battery found. Exiting...")
                break
            
            percentage = battery.percent
            power_plugged = battery.power_plugged
            
            print(f"? Battery Monitor")
            print(f"{'='*20}")
            print(f"Charge: {percentage}%")
            
            # Battery status indicator
            if percentage >= 80:
                status = "? Excellent"
            elif percentage >= 50:
                status = "? Good"
            elif percentage >= low_battery_threshold:
                status = "? Fair"
            else:
                status = "? LOW BATTERY!"
            
            print(f"Status: {status}")
            print(f"Adapter: {'? Connected' if power_plugged else '? On Battery'}")
            
            # Low battery warning
            if percentage <= low_battery_threshold and not power_plugged:
                print(f"\n??  WARNING: Battery below {low_battery_threshold}%!")
                print("Please connect your charger.")
            
            print(f"\nRefreshing in {refresh_interval} seconds...")
            print("Press Ctrl+C to exit")
            
            time.sleep(refresh_interval)
            
    except KeyboardInterrupt:
        print("\n\nBattery monitoring stopped.")

# Run the monitor (uncomment to use)
# monitor_battery(refresh_interval=30, low_battery_threshold=25)

Running the Scripts

Save any of the scripts with a .py extension and run them using ?

python battery_monitor.py

For the continuous monitoring script, use Ctrl+C to stop execution.

Key Features

Feature Basic Script Enhanced Script Monitor Script
Battery Percentage ? ? ?
Power Adapter Status ? ? ?
Time Remaining ? ? ?
Continuous Monitoring ? ? ?
Low Battery Warning ? ? ?

Conclusion

Python's psutil library makes it easy to create battery monitoring scripts for laptops. These scripts can range from simple one-time checks to continuous monitoring systems with warnings and detailed status information.

Updated on: 2026-03-27T12:12:05+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements