Write a Python Script to Notify the Current Battery Percentage in Windows

Write a Python Script to Notify the Current Battery Percentage in Windows

Overview

This article explains how to create custom notifications for any Python script and as an example, showcases how to notify users what the current battery percentage is for their Windows laptop. Two scripts that use different Python modules will be showcased how to create notifications that displays the battery percentage.

Purpose

This script is intended to display a Windows laptop's current battery status. This is useful since Windows usually notifies users when the battery is low, but never notifies them when it is at a high percentage or 100%. This script will notify the user when the battery is at a high percentage so it can be removed from the charger to prevent overcharging it.

Materials

  • Windows

  • Python

    • Required Python Packages: subprocess

    • Required Python Packages that need to be downloaded for the first script: win10toast (1), pypiwin32

    • Required Python Packages that need to be downloaded for the second script: windows_toasts (2). To use these packages, Python 3.8 or greater and Windows 10 or a later version must be installed.

  • Command Prompt, PowerShell or preferred IDE

First Script Context: Which Modules are being used and Why

Since a Python script is being written and interacting with the Windows operating system, the module subprocess is needed. Subprocess is used to read Windows commands and execute them in Python scripts. Subprocess is a module already installed in Python, therefore no packages are not needed to download to use it.

The module called ToastNotifier needs the packages "win10toast" and "pypiwin32" to be downloaded in order to use it. Downloading the "win10toast" package first by performing "pip install win10toast" automatically installs the "pypiwin32" package too.

Procedure: Writing the First Script

Begin writing the script by importing the needed modules:

#!/usr/bin/env python3

import subprocess
from win10toast import ToastNotifier

The Windows command to execute the received the battery charge is:

"WMIC PATH Win32_Battery Get EstimatedChargeRemaining"

Executing the command "WMIC PATH Win32_Battery Get EstimatedChargeRemaining" in Command Prompt or PowerShell gives an output similar to the image below:

Usually, trying to directly cast a statement like this in Python to a string, would not work. Using the package subprocess accurately reads the Windows command and then it can be casted to be used afterward. The Windows command has been assigned to the variable called "battery_percent_string":

#!/usr/bin/env python3

import subprocess
from win10toast import ToastNotifier

battery_percent_string = "WMIC PATH Win32_Battery Get EstimatedChargeRemaining"
check_battery_percent = subprocess.check_output(battery_percent_string, shell=True)

The variable "check_battery_percent" has been assigned to use the "subprocess.check_output" on the variable "battery_percent_string" to give an output that can be modified. The parameter "shell=True" is included and defined this way since this command is being executed in either PowerShell or Command Prompt. Below is the output if "check_battery_percent" is printed:

Though the output looks awkward, it still shows "EstimatedChargeRemaining" and the number that signifies the battery charge. To find the index of the battery charge or in this case, 60, a temporary for loop can find the indexes where the battery charge is.

# For loop
index = 0
for i in str_battery_percent:
    print(index, str_battery_percent[index])
    index += 1

After using the for loop, the indexes that contain the battery charge are at positions 34, 35 and 36. Since the number is only wanted from the variable "str_battery_percent", these indexes can be added together and assigned to the variable "battery_percentage".

#!/usr/bin/env python3

import subprocess
from win10toast import ToastNotifier

battery_percent_string = "WMIC PATH Win32_Battery Get EstimatedChargeRemaining"
check_battery_percent = subprocess.check_output(battery_percent_string, shell=True)

str_battery_percent = str(check_battery_percent)

if str_battery_percent[36] == "0":
  battery_percentage = str_battery_percent[34] + str_battery_percent[35] + str_battery_percent[36]
elif str_battery_percent[35] != " ":  
  battery_percentage = str_battery_percent[34] + str_battery_percent[35]
else:
  battery_percentage = str_battery_percent[34]

An if-else statement is included to check if the battery percentage is 100%, then index position 36 will always contain a "0". If the battery percentage is not 100%, then the elif statement will be performed and add index positions 34 and 35 together, otherwise, the else statement will be executed if position 35 is empty.

Since "battery_percentage" is still a string, it needs to be casted to an integer as a different variable, which is called "int_battery_percentage". Another if-else statement is incorporated to check if the battery is at 100% or a different integer value. Down below, the toast module is used to make the notification.

#!/usr/bin/env python3
# Final Script

import subprocess
from win10toast import ToastNotifier

battery_percent_string = "WMIC PATH Win32_Battery Get EstimatedChargeRemaining"
check_battery_percent = subprocess.check_output(battery_percent_string, shell=True)

str_battery_percent = str(check_battery_percent)

if str_battery_percent[36] == "0":
  battery_percentage = str_battery_percent[34] + str_battery_percent[35] + str_battery_percent[36]
elif str_battery_percent[35] != " ":  
  battery_percentage = str_battery_percent[34] + str_battery_percent[35]
else:
  battery_percentage = str_battery_percent[34]

int_battery_percentage = int(battery_percentage)

display_message = ToastNotifier()

if int_battery_percentage == 100:
  display_message.show_toast("BATTERY LEVEL", "Battery is at {}%".format(battery_percentage), duration=10)
else:
  display_message.show_toast("BATTERY LEVEL", "Battery is at {}%".format(battery_percentage), duration=10)

A variable needs to be declared to initiate the ToastNotifier function. In this case, the variable display_message was created. Afterward, the variable must be written with the method "show_toast" to write a notification. The "variable".show_toast("", "", "", "") takes four parameters:

  • Parameter 1: Title of Notification Alert

  • Parameter 2: Description of Notification Alert

  • Parameter 3: How long the alert displays on the screen in seconds before it leaves

  • Parameter 4: Include a picture. This is optional. If no picture is included, then a picture of the Python logo is used instead.

Demonstration: Running the First Script

Below, are examples of how the notification works when executed:

Second Script Context: Which Modules are being used and Why

This script uses the following modules: subprocess, WindowsToaster and Toast. Before using WindowsToaster and Toast, the package windows_toasts need to be downloaded and can be done by performing "python -m pip install windows-toasts".

Procedure: Writing the Second Script

Begin the script by importing the needed modules:

#!/usr/bin/env python3

import subprocess
from windows_toasts import WindowsToaster, Toast

The same code to retrieve the battery percentage from Windows is still used and converted to a string:

#!/usr/bin/env python3

import subprocess
from windows_toasts import WindowsToaster, Toast

battery_percent_string = "WMIC PATH Win32_Battery Get EstimatedChargeRemaining"
check_battery_percent = subprocess.check_output(battery_percent_string, shell=True)

str_battery_percent = str(check_battery_percent)

The same code is also used in the second script to retrieve the indexes of the battery percentage. If the battery percentage is 0% to 9%, then the index 34 is only retrieved. If the battery percentage is from 10% to 99%, then indices 34 and 35 are retrieved. If the battery percentage is 100%, then the battery percentage indices 34, 35 and 36 are retrieved. An if-elif-else statement has been implemented to check for these conditions:

#!/usr/bin/env python3

import subprocess
from windows_toasts import WindowsToaster, Toast

battery_percent_string = "WMIC PATH Win32_Battery Get EstimatedChargeRemaining"
check_battery_percent = subprocess.check_output(battery_percent_string, shell=True)

str_battery_percent = str(check_battery_percent)

if str_battery_percent[36] == "0":
  battery_percentage = str_battery_percent[34] + str_battery_percent[35] + str_battery_percent[36]
elif str_battery_percent[35] != " ":  
  battery_percentage = str_battery_percent[34] + str_battery_percent[35]
else:
  battery_percentage = str_battery_percent[34]

Lastly, the code is implemented to use the toast notification:

#!/usr/bin/env python3
# Final Script

import subprocess
from windows_toasts import WindowsToaster, Toast

battery_percent_string = "WMIC PATH Win32_Battery Get EstimatedChargeRemaining"
check_battery_percent = subprocess.check_output(battery_percent_string, shell=True)

str_battery_percent = str(check_battery_percent)

if str_battery_percent[36] == "0":
  battery_percentage = str_battery_percent[34] + str_battery_percent[35] + str_battery_percent[36]
elif str_battery_percent[35] != " ":  
  battery_percentage = str_battery_percent[34] + str_battery_percent[35]
else:
  battery_percentage = str_battery_percent[34]

toaster = WindowsToaster('Python')
newToast = Toast()
sentence_stating_current_battery = "The current battery percentage is " + battery_percentage + "%"
newToast.text_fields = [sentence_stating_current_battery]

toaster.show_toast(newToast)

The line "toaster = WindowsToaster('Python')" initializes the toaster to be used with Windows and the Python programming language.

Afterward, the line "newToast = Toast()" creates the notification box pop-up when the script is run.

The line "sentence_stating_current_battery = "The current battery percentage is " + battery_percentage + "%" " is the sentence that will be displayed when the notification appears.

newToast.text_fields = [sentence_stating_current_battery] displays the statement or sentence that is desired to appear in the notification box.

The command "toaster.show_toast(newToast)" will show the customized notification.

Demonstration: Running the Second Script

Sources

https://pypi.org/project/win10toast/ (1)

https://windows-toasts.readthedocs.io/en/latest/getting_started.html#quickstart (2)

Source Code

https://github.com/AndrewDass1/SCRIPTS/tree/main/Windows/Python/Check%20Battery