Last active
December 17, 2023 20:30
-
-
Save android10/7dbbbc8f07ab70b6d44ca662f20d0b4e to your computer and use it in GitHub Desktop.
Tiny Python script for Linux Users to notify when Battery Level is low. Use it with a cronjob
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
""" | |
This script aims to alert when the battery | |
reaches a critical level in the system. | |
""" | |
import os | |
CRITICAL_BATTERY_PERCENTAGE = 8 | |
CMD_NOTIFY_USER = "notify-send 'LOW BATTERY LEVEL' -u critical" | |
def check_battery_status(): | |
"""Check main battery status.""" | |
battery_status = current_battery_status() | |
battery_level = current_battery_level() | |
if battery_status == "Discharging" and battery_level == CRITICAL_BATTERY_PERCENTAGE: | |
notify_user() | |
def current_battery_level(): | |
""" | |
Return surrent system | |
battery level from: | |
/sys/class/power_supply/BAT0/capacity | |
""" | |
with open("/sys/class/power_supply/BAT0/capacity", "r") as battery_level: | |
return int(battery_level.read()) | |
def current_battery_status(): | |
""" | |
Return surrent system | |
battery status from: | |
/sys/class/power_supply/BAT0/status | |
""" | |
with open("/sys/class/power_supply/BAT0/status", "r") as battery_status: | |
return battery_status.readline().strip() | |
def notify_user(): | |
""" | |
Notifies the user. | |
$ notify-send "LOW BATTERY" -u critical | |
""" | |
os.system("/bin/bash -c \"" + CMD_NOTIFY_USER + "\"") | |
if __name__ == "__main__": | |
check_battery_status() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment