简体   繁体   中英

How to do a notification in an If statement but continue a While loop in Python?

I'm using psutil and Python to notify me when I'm on battery power or AC power. I have a while loop that continuously checks for battery power. I want it to notify me when we're on battery power, but only once. If I declare the variable power_notification = 0 anywhere, it will reset it to 0 when the while loop runs again. How do I keep the count so it only notifies me once until we're back on AC? I get no errors but it continuously print that's we're on battery power.

import psutil

power_good = True

def check_power_status():
    power_notification = 0
    battery = psutil.sensors_battery()
    plugged_in = battery.power_plugged
    percent = str(battery.percent)

    if not plugged_in:
        if power_notification == 0:
            plugged_in = "We are on battery power."
            print(plugged_in + "\n" + "You have " + percent + "% of your battery remaining.")
            power_notification = 1
        else:
            power_good = False
            return power_good
    else:
        power_good = True
        return power_good

while power_good:
    check_power_status()

I believe the only things you need to do is make power_notification global and reset it to 0 when the power is good:

import psutil

power_good = True
power_notification = 0

def check_power_status():
    battery = psutil.sensors_battery()
    plugged_in = battery.power_plugged
    percent = str(battery.percent)

    if not plugged_in:
        if power_notification == 0:
            plugged_in = "We are on battery power."
            print(plugged_in + "\n" + "You have " + percent + "% of your battery remaining.")
            power_notification = 1
        else:
            power_good = False
            return power_good
    else:
        power_good = True
        power_notification = 0
        return power_good

while power_good:
    check_power_status()

Does that answer your question?

You need to keep it running as daemon so while should have True all the time. So I can't see any reason for using power_good .

The power_notification should be outside the function to maintain its value.

import psutil

power_notification = 0

def check_power_status():
    global power_notification
    battery = psutil.sensors_battery()
    plugged_in = battery.power_plugged
    percent = str(battery.percent)

    if not plugged_in:
        if power_notification == 0:
            plugged_in = "We are on battery power."
            print(plugged_in + "\n" + "You have " + percent + "% of your battery remaining.")
            power_notification = 1
    #AC plugged_in 
    else:
        power_notification = 0

while True:
    check_power_status()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM