一、upower获取
apt install upower
执行如下命令:
upower --dump | grep --color=never -E "state|to\ full|to\ empty|percentage"
如果笔记本连接电源,待充电,则显示如下:
state pending-charge
percentage: 99%
若未连接电源:
state: discharging
time to empty: 17.9 hours
percentage: 97%
接电源充电:
state: charging # 充电
time to full: 11.2 minutes # 多久充满
percentage: 98%
充满:
state: fully-charged
percentage: 100%
可以根据state判断展示情况
二、psutil模块获取
代码如下:
def get_battery_remaining():
resp = {
'percent': 100, 'power_plugged': True, 'remain_time': 'unlimited'
}
if psutil.sensors_battery():
resp['percent'] = round(psutil.sensors_battery().percent)
resp['power_plugged'] = psutil.sensors_battery().power_plugged
if not resp['power_plugged']:
resp['remain_time'] = '%.2f' % (psutil.sensors_battery().secsleft / 60 / 60)
return response(resp)
但是按照psutil获取,剩余时间有点不稳定,变化较大