參考鏈接: 從Python中控制臺獲取輸入
把開發者模式打開,激活 adb 調試,然后可以使用以下python代碼獲取安卓手機的耗電量?
# -*- coding: utf-8 -*-
?
import re
import os
?
def getSelectDevice():
? ? pip = os.popen('adb devices')
? ? result = pip.read()
? ? devices_split = result.split('\n')
? ? devices = []
? ? for device in devices_split:
? ? ? ? if device == '':
? ? ? ? ? ? continue
? ? ? ? devices.append(device)
? ? ? ?
? ? if len(devices) < 2:
? ? ? ? print('設備不存在')
? ? ? ? return -1
? ??
? ? if len(devices) == 2: # 只有一臺設備,直接返回
? ? ? ? return devices[1].split('\t')[0]
? ??
? ? print("選擇你要操作的設備")
? ? for index in range(1,len(devices)):
? ? ? ? print("%s:\t%s" % (index,devices[index]))
?
?
? ? print("輸入編號:")
? ? select=int(input())
? ? selectline = devices[select]
? ? return selectline.split('\t')[0]
? ??
def getBatteryInfo(device):
? ? pip = os.popen('adb -s %s shell dumpsys batterystats' % device)
? ? result = pip.buffer.read().decode(encoding='utf8')
? ? return result
? ??
def parsePowerInfo(info):
? ??
? ? start = 0
? ??
? ? try:
? ? ? ? start = info.index('Estimated power use')
? ? except Exception:
? ? ? ? print('耗電量信息不存在')
? ? ? ? return -1
? ? if start < 0:
? ? ? ? print('耗電量信息不存在')
? ? ? ? return -1
? ? start = info.index('Capacity',start)
? ? end = info.index('\n',start)
? ? ? ??
? ? result = info[start:end]
? ??
? ? capacity = re.findall('\d+\.?\d*', result)
? ??
? ? return capacity
?
def parseResetTimeInfo(info):
? ??
? ? start = 0
? ??
? ? try:
? ? ? ? start = info.index('RESET:TIME:')
? ? except Exception:
? ? ? ? print('重置時間不存在')
? ? ? ? return -1
? ? if start < 0:
? ? ? ? print('重置時間不存在')
? ? ? ? return -1
? ? end = info.index('\n',start)
? ? ? ??
? ? result = info[start:end]
? ??
? ? capacity = re.findall('\d+\.?\d*', result)
? ? return capacity
? ??
?
?
?
def main():
? ? device = getSelectDevice()
? ? if device == -1:?
? ? ? ? return
? ? print("正在獲取信息...")
? ? betteryinfo = getBatteryInfo(device)
? ? if betteryinfo == -1:?
? ? ? ? return
? ? print("正在解析信息...")
? ? result = parsePowerInfo(betteryinfo)
? ? if result == -1:?
? ? ? ? return
? ??
? ? print("得出結果:")
? ? print("\t電池容量:%s mA" % (result[0]))
? ? print("\t計算耗電:%s mA" % (result[1]))
? ? print("\t實際耗電:%s mA" % (result[2]))
? ??
? ? timeinfo = parseResetTimeInfo(betteryinfo)
? ? if timeinfo == -1:
? ? ? ? return
? ? print("重置時間:%s-%s-%s %s:%s:%s" % (timeinfo[0],timeinfo[1],timeinfo[2],timeinfo[3],timeinfo[4],timeinfo[5]))
? ? pass
?
if __name__ == '__main__':
? ? main()
? ? pass
? ? ? ??
?
我這邊接入了兩個設備的控制臺輸出:?
選擇你要操作的設備
1:? ? ? 192.168.0.103:5555? ? ? device
2:? ? ? 192.168.0.101:5555? ? ? device
輸入編號:
?
2
正在獲取信息...
正在解析信息...
得出結果:
? ? ? ? 電池容量:3300 mA
? ? ? ? 計算耗電:282 mA
? ? ? ? 實際耗電:396 mA
重置時間:2020-07-20 11:22:37