|
|
楼主 |
发表于 2025-11-8 14:51:52
|
显示全部楼层
延长笔记本电池寿命的Python脚本。原理很简单:充电到80%提醒停止充电,放电到20%提醒充电,避免过放。理论上可大幅延长笔记本电池使用寿命。
- #!/usr/bin/env python3
- import os
- from time import sleep
- SYS_PREFIX = '/sys/class/power_supply'
- MAX = 80
- MIN = 20
- WAIT = 3 * 60
- # 返回交流电的设备名及状态,True 表示接通,False 表示未接通
- def detect_ac_adapter():
- for device in os.listdir(SYS_PREFIX):
- device_path = os.path.join(SYS_PREFIX, device)
- if os.path.isdir(device_path):
- status_file = os.path.join(device_path, 'online')
- if os.path.isfile(status_file):
- with open(status_file, 'r') as f:
- status = f.read().strip()
- return device, status == '1'
-
- def detect_battery():
- for device in os.listdir(SYS_PREFIX):
- device_path = os.path.join(SYS_PREFIX, device)
- if os.path.isdir(device_path):
- status_file = os.path.join(device_path, 'capacity')
- if os.path.isfile(status_file):
- with open(status_file, 'r') as f:
- return device, int(f.read().strip())
- return None, None
- def send_notification(message):
- os.system("notify-send '{}' '{}'".format('充电提醒', message))
- def performance_check():
- ac_adapter, ac_online = detect_ac_adapter()
- battery, capacity = detect_battery()
- if battery and capacity <= MIN and (not ac_online):
- send_notification(f'电量少于{MIN}%,请充电!')
- if battery and capacity >= MAX and ac_online:
- send_notification(f'电量大于{MAX}%,请移除外接电源!')
-
- if __name__ == '__main__':
- while True:
- performance_check()
- sleep(WAIT)
复制代码 |
|