如何使用Python创建电池通知程序

2024-04-16 20:47:38 发布

您现在位置:Python中文网/ 问答频道 /正文

笔记本电脑电池充电总是很紧张。我经常忘记给笔记本电脑充电,好像在检查电池。所以我希望我的脚本在我的笔记本电脑电池电量为80%和20%时给我一个通知

我正试图安装派勒,但idk,如果它是一个库错误或其他东西

如果你知道我们可以用另一种方式做这件事,请详细回答我

这是我的代码:

import psutil
from pyler import notification
import time
 
while(True):
    battery = psutil.sensors_battery()
    percent = battery.percent

    notification.notify(
        title="Battery Percentage",
        message=str(percent)+"% Battery remaining",
        timeout=10
    )

    time.sleep(2*2)
    continue

我试图安装派勒,但我不知道这是图书馆的问题还是我的电脑

无论如何,谢谢你的帮助


Tags: import脚本电池time错误方式notificationpsutil
1条回答
网友
1楼 · 发布于 2024-04-16 20:47:38

那么,为什么不使用另一个程序包作为通知,您可以通过运行

pip install win10toast

假设您正在运行Windows 10。我修改了你的代码,让它工作

import os
import psutil
import platform
from time import sleep
from win10toast import ToastNotifier

toaster = ToastNotifier()

def Alert(title, msg, duration=10):
    if platform.system() == 'Windows':
        toaster.show_toast(title, msg, duration=duration)
    elif platform.system() == 'Linux':
        os.system("notify-send '" + title + "' '" + msg + "'")

while True:
    percent = psutil.sensors_battery().percent
    
    if percent <= 20:
        msg = 'The battery is very low and draining, Its time to feed the hunger of batter'
        Alert('Battery Alert', msg)
        
    print('Battery Remaining', str(percent) + '%')
    sleep(1)
    os.system("clear || cls")

该代码适用于Linux(Ubuntu)和Windows,如果您在使用此通知包时遇到问题,可以尝试使用其他包,例如PyQT5Tkinter,它们都是跨平台的,几乎可以在所有主要操作系统上使用

或者,如果您仍然熟悉plyer,则通过运行

pip install plyer

您拼错了程序包,还更新了代码,如下所示

import psutil
from plyer import notification
import time
 
while(True):
    battery = psutil.sensors_battery()
    percent = battery.percent

    notification.notify(
        title="Battery Percentage",
        message=str(percent)+"% Battery remaining",
        timeout=10
    )

    time.sleep(2*2)
    continue

相关问题 更多 >