当我使用电池电源或交流电源时,我正在使用psutil和Python通知我。我有一个while循环,可以连续检查电池电量。我希望它在使用电池供电时通知我,但只能通知一次。如果我在任何地方声明变量power_notification = 0,则它将在while循环再次运行时将其重置为0。我该如何保存计数,这样它才通知我一次,直到我们重新使用AC为止?我没有收到任何错误,但它不断打印,表明我们使用电池供电。
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()
答案 0 :(得分:1)
我相信您唯一需要做的就是全局设置 power_notification ,并在电源良好时将其重置为0:
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()
这能回答您的问题吗?
答案 1 :(得分:1)
您需要保持它以new_col_headers, *new_col_bodies = new_cols.transpose
#=> [["age", "iq"], [22, 85], [110, 140]]
new_col_headers
#=> ["age", "iq"]
new_col_bodies
#=> [[22, 85], [110, 140]]
new_col_bodies = new_col_bodies.transpose
#=> [[22, 110], [85, 140]]
的身份运行,因此daemon
应该一直都while
。因此,我看不出使用True
的任何理由。
power_good
应该在函数之外,以保持其值。
power_notification