我的脚本运行一次,如何编码使其始终运行?

我一般是python和编程新手。我编写了一个小脚本,当电池电量达到100%或低于25%时会通知我。对于单个实例,它运行良好。我正在尝试使其始终运行,即它位于托盘中并根据条件弹出通知。我尝试将整个过程置于“ while True:”循环中,但这似乎无济于事。你们可以帮我吗?

代码:-

import psutil
from win10toast import ToastNotifier
toaster=ToastNotifier()
while True:
    def battery():
        val=psutil.sensors_battery()
        percent=val.percent
        power=val.power_plugged
        if percent<25 and power==False:
            return ('We\'re low on power({}%),plug in the charger.'.format(percent))
        elif percent>=100 and power==True:
            return ('Fully charged ({}%),you can disconnect the charger now.'.format(percent))
    try:
        toaster.show_toast('BatteryMeter',battery(),'c:/users/sanoop/desktop/Battery.ico',duration=5)
    except:
        pass```


xuzhihua131792 回答:我的脚本运行一次,如何编码使其始终运行?

您需要在一段时间内例行调用battery(),而无需其他任何操作。 因此,例如,考虑其余代码,则保持不变:

while True:
  battery()
  time.sleep(1)
本文链接:https://www.f2er.com/3093014.html

大家都在问