Created
November 27, 2023 11:18
-
-
Save samj/7f3034d39b00b11872c1f0c112d0c37e to your computer and use it in GitHub Desktop.
A Python script to monitor MacBook battery health. It checks the battery's maximum capacity and sends a macOS notification if the capacity falls to 80% or below. Useful for keeping an eye on battery health and knowing when it might be time to consider servicing or replacing the MacBook's battery.
This file contains 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 | |
import subprocess | |
import re | |
import os | |
def get_battery_health(): | |
# Run the system_profiler command to get battery information | |
result = subprocess.run(["/usr/sbin/system_profiler", "SPPowerDataType"], capture_output=True, text=True) | |
output = result.stdout | |
# Extract the battery health percentage using regular expression | |
match = re.search(r"Maximum Capacity:\s+(\d+)%", output) | |
if match: | |
return int(match.group(1)) | |
else: | |
return None | |
def send_notification(message): | |
# Send a macOS notification | |
command = f''' | |
osascript -e 'display notification "{message}" with title "Battery Health Alert"' | |
''' | |
os.system(command) | |
def main(): | |
health = get_battery_health() | |
if health is None: | |
print("Unable to determine battery health.") | |
elif health <= 80: | |
# print(f"Current battery health: {health}%") | |
send_notification(f"Battery health is at or below 80% ({health}%). Consider servicing your battery.") | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment