如何使用Python创建电池电量通知工具,pyler库安装异常如何解决?
问题排查与解决方案
一、pyler库报错排查
你遇到的导入错误90%是拼写问题,正确的通知库名称是plyer而非pyler,按以下步骤修复:
- 先卸载错误安装的包:
pip uninstall pyler -y - 安装正确的依赖包:
pip install plyer psutil - 将代码里的导入语句改为
from plyer import notification
二、功能逻辑修正
你当前的代码会每4秒弹窗一次,不符合「仅电量达到20%、80%阈值时推送」的需求,修正后的完整代码如下:
import psutil from plyer import notification import time # 记录上一次推送的阈值,避免重复推送 last_notify = None while True: battery = psutil.sensors_battery() percent = battery.percent is_charging = battery.power_plugged # 低电量提醒:电量≤20%且未充电时推送 if percent <= 20 and not is_charging and last_notify != "low": notification.notify( title="低电量提醒", message=f"当前电量仅剩{percent}%,请及时连接电源", timeout=10 ) last_notify = "low" # 高电量提醒:电量≥80%且充电中时推送 elif percent >= 80 and is_charging and last_notify != "high": notification.notify( title="电量充足提醒", message=f"当前电量已达{percent}%,建议断开电源延长电池寿命", timeout=10 ) last_notify = "high" # 电量处于中间区间时重置标记 elif 20 < percent < 80: last_notify = None # 每60秒检测一次即可,不需要太频繁 time.sleep(60)
三、plyer不可用时的替代方案
如果修正拼写后还是无法正常推送,按操作系统选择替代方案:
Windows系统
使用win10toast库实现通知:
- 安装依赖:
pip install win10toast psutil - 替换通知部分代码:
from win10toast import ToastNotifier toaster = ToastNotifier() # 推送通知时调用 toaster.show_toast(title="提醒标题", msg="提醒内容", duration=10)
MacOS系统
使用系统自带的AppleScript实现通知,不需要额外安装通知库:
import os # 推送通知时调用 os.system(f''' osascript -e 'display notification "提醒内容" with title "提醒标题"' ''')
Linux系统
调用系统自带的notify-send命令实现通知:
import os # 推送通知时调用 os.system(f'notify-send "提醒标题" "提醒内容" -t 10000')
内容的提问来源于stack exchange,提问作者Kirito-Kun
相关产品推荐
相关产品推荐

