0

I'm a beginner programmer and I'm trying to write some code that would show a messagebox whenever my battery level gets to either 1% or 100%. With the code below, I'm able to get the messagebox whenever I run the program at the same time as when my battery is either at 1 or 100. However, whenever it isn't, the messagebox doesn't appear, even when it eventually reaches either of those two numbers. My program keeps running as I have a While loop so it should trigger when it reaches 1 or 100 but it doesn't and I'm not sure why. Some help would be greatly appreciated. Thanks!

import os
import subprocess
from tkinter import *
import tkinter.messagebox

# Terminal command to get the Battery percentage
batLevel = subprocess.run(['''pmset -g batt | grep -Eo "\d+%" | cut -d% -f1'''], shell=True, capture_output=True, encoding="utf", errors="ignore")
batLevel = batLevel.stdout.split("\n")[0]
batLevel = int(batLevel)

# Popup Window
def popup(msg=""):
    root=Tk()
    tkinter.messagebox.showerror(title=None, message=msg)
    root.mainloop()

while True:
    if batLevel == 100:
        popup("BATTERY FULL")
    elif batLevel == 1:
        popup("LOW BATTERY")
    else:
        continue
c0nfluks
  • 53
  • 5
  • There's no code inside of your `while` loop that can possibly change the value of `batLevel`; whichever branch of code is taken on the first loop, will be taken on all further loops. – jasonharper May 15 '22 at 03:18
  • The value changes itself because it looks at the battery percentage, it is not an arbitrary value. But it seems like the `while` loop doesn't keep looking at the value as it changes. – c0nfluks May 15 '22 at 04:50
  • Your program read the battery level *ONCE*, as it was starting up. Which of the 7 lines of the `while` loop do you believe might update that value? – jasonharper May 15 '22 at 15:12
  • I'm new to this, I don't know. Hence why I'm asking. I didn't believe I had to update the value as I thought it updates itself because it's a battery level check. I'm asking for help. – c0nfluks May 15 '22 at 18:04
  • You need to move those three lines that read the battery level into the loop, so that you have a current reading each time. – jasonharper May 15 '22 at 18:40
  • That makes sense, it worked. thanks a lot! – c0nfluks May 15 '22 at 19:05
  • As an aside, it would perhaps be more robust to run just `subprocess.run(["pmset", "-g", "batt"], capture_output=True, text=True)` without `shell=True` and do the parsing of the output in Python. The code will be a bit more verbose, but also easier to maintain for anyone who is not conversant in both Python and shell script. – tripleee May 16 '22 at 09:26
  • `encoding="utf"` is not strictly well-defined. Python apparently interprets this as `"utf-8"` but that's quite obscure. – tripleee May 16 '22 at 09:28

0 Answers0