python手机代码查询命令_用 Python 脚本及 adb 命令查看设备的 CPU 使用率

测试小哥最近需要查看一个设备的进程和 CPU 的使用情况,但系统日志的输出格式很杂乱于是就动手写脚本代码来查看输出结果。虽然他提供了代码,但还是想自己动手简单尝试一下。

本例子是查看手机的进程及 CPU 使用情况,简化了一些部分,分为下面几个步骤完成。获取设备名

(如果电脑只连接了一个设备,这步是不需要的。但在连接多个设备的情况下需要获取对应的设备名,那么代码就需要进行修改。)

第一步是通过 adb 命令:adb devices 获取设备名,如下图所示,需要的是 「LGH860B53E9225」 这一串信息:

具体的 Python 脚本为:import os

def get_device():

deivce = os.popen('adb devices').read()

out = device.split(' ')[3].split('\n')[1].split('\t')[0]

return out

-----------

get_device()

Out[28]:

'LGH860b53e9225'读取设备进程状态def get_pid():

## 此处把 adb 的命令写死了,获得最大进程数为 3 条且迭代 1 次的情况 ,有时间再稍作修改

pid = os.popen('adb shell top -m 3 -n 1 ').read()

out = pid.split('\n')[4:7]

return out

---------

get_pid()

Out[101]:

['28895 shell 20 0 23% R 1 9144K 2060K fg top',

' 2 root 20 0 0% S 1 0K 0K fg kthreadd',

' 3 root 20 0 0% S 1 0K 0K fg ksoftirqd/0']只获取 CPU 那一列的数据def del_space(l):

new_list = []

for i in range(len(l)):

if l[i] != '':

new_list.append(l[i])

return new_list

def get_cpu(l):

new_list = []

for i in range(len(get_pid())):

new_iterm = del_space(get_pid()[i].split(' '))[4]

new_list.append(new_iterm)

return new_list

-------

get_cpu(del_space(get_pid()))

Out[128]:

['20%', '0%', '0%']计算实时 CPU 使用率def cal_cpu(l):

cpu_prob = 0

for i in range(len(l)):

new_iterm = l[i].split('%')[0]

cpu_prob += int(new_iterm)

return "实时 CPU 使用率为:" + str(cpu_prob) + '%'

-----------

cal_cpu(get_cpu(del_space(get_pid())))

Out[122]:

'实时 CPU 使用率为:24%'CPU 使用率超出 10 % 存为 txt 文件

因为获取的数据是比较简单的,且单行累积记录,所以存入 txt 文件会比较简单。如果数据是很复杂的,存为 Excel / csv 文件会比较清晰,且也容易进行数据分析。下面会给出 txt 和 Excel 两种方法。import datetime

def save_txt(int_cpu_num):

if int_cpu_num > 10 :

time = datetime.datetime.now()

time_print = time.strftime('%Y.%m.%d-%H:%M:%S') # 时间戳

cpu_info = "IOT总使用CUP为"+ " " + str(int_cpu_num)+" %"

info = str(time_print) + ' : ' +str(cpu_info)

file = open('cpu.txt', 'a') # ‘a’为追加模式

file.write(info + "\n")import xlwt #写入模块

import xlrd #读取模块

import os

import datetime

from xlutils.copy import copy

def save_excel(int_cpu_num):

path = 'C:/Users/Administrator/Desktop/cpu.xls'

p =os.path.exists(path)

if p == False:

if int_cpu_num > 10 :

workbook = xlwt.Workbook(encoding='utf-8')

sheet = workbook.add_sheet('CPU')

workbook.save(path)

data = xlrd.open_workbook(path)

table = data.sheets()[0]

nrows = table.nrows # 获取行数

# print(nrows)

excel = copy(data)

sheet = excel.get_sheet(0)

time = datetime.datetime.now()

time_print = time.strftime('%Y.%m.%d-%H:%M:%S')

cpu_info = "IOT总使用CUP为"+ " " + str(int_cpu_num)+" %"

info = str(time_print) + ' : ' +str(cpu_info)

sheet.write(nrows , 0, info)

excel.save(path)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值