测试小哥最近需要查看一个设备的进程和 CPU 的使用情况,但系统日志的输出格式很杂乱于是就动手写脚本代码来查看输出结果。虽然他提供了代码,但还是想自己动手简单尝试一下。
本例子是查看手机的进程及 CPU 使用情况,简化了一些部分,分为下面几个步骤完成。
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']
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%']
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%'
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)