# -*- coding: utf-8 -*-
# -------------------------------
# @时间:2024/6/26 20:06
# @文件:battery.py
import subprocess
def get_devices():
"""获取设备sn列表"""
sn_list = []
try:
output = subprocess.check_output(['adb', 'devices'])
except subprocess.CalledProcessError as e:
print("Error:", e.output)
return None
for line in output.decode('utf-8').splitlines():
if line.endswith("device"):
sn = line.split()[0]
sn_list.append(sn)
return sn_list
def get_battery_info(sn):
"""获取电池百分比,充电状态"""
try:
output = subprocess.check_output(['adb', '-s', sn, 'shell', 'dumpsys', 'battery'])
except subprocess.CalledProcessError as e:
print("Error:", e.output)
return None
level, charge_status = None, None
for line in output.decode('utf-8').splitlines():
if "level" in line:
level = line.split()[1]
if "status" in line:
charge_status = line.split()[1]
return int(level), int(charge_status)
def set_battery_charge(sn, level, charge_status):
"""设置手机电池状态"""
if level:
if level <= 50 and charge_status == 0:
status = 2
elif level >= 90 and charge_status == 2:
status = 0
else:
return None
try:
print(f'{sn} battery level is {level}')
cmd = ['adb', '-s', sn, 'shell', 'dumpsys', 'battery', 'set', 'status', f'{status}']
print(cmd)
output = subprocess.check_output(cmd)
except subprocess.CalledProcessError as e:
print("Error:", e.output)
def battery_manager():
sn_list = get_devices()
if len(sn_list) > 0:
for sn in sn_list:
level, charge_status = get_battery_info(sn)
if level and charge_status:
set_battery_charge(sn, level, charge_status)
else:
print(f"{sn} get battery info fail!")
else:
print(f"未获取到设备列表")
if __name__ == '__main__':
battery_manager()
``
Python 安卓手机电池管理
最新推荐文章于 2024-08-13 18:29:56 发布