【问题标题】:My script runs once, how do I code it to run always?我的脚本运行一次,如何将其编码为始终运行?
【发布时间】:2019-11-15 19:32:07
【问题描述】:

我是 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```


【问题讨论】:

  • 您没有像以前那样调用电池功能。
  • @stovfl 已编辑。当我这样做时,即使不满足条件,它也会创建系统托盘图标的无限循环。当它遇到时,与通知相同的无限循环。我明白这是意料之中的。
  • 你不需要将函数定义放在while循环中,只要函数就足够了。
  • @sanoop:查看repl.it的模拟
  • @stovfl 谢谢,我会试试这个。

标签: python notifications widget system-tray


【解决方案1】:

您需要在 while 中例行调用 battery(),仅此而已。 因此,例如,考虑到您的其余代码保持不变:

while True:
  battery()
  time.sleep(1)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-18
    • 2020-04-10
    相关资源
    最近更新 更多