正所謂磨刀不誤砍柴工。結合昨天說的adb shell top指令,今天說的xlwt模塊的調用以及Excel表格中文本格式的轉換;我們就可以開始使用Python/ target=_blank class=infotextkey>Python來編寫CPU占用率的腳本。
一、腳本編寫的框架
在腳本編寫前我們需要打個框架,然后才能逐步往下走。
1、先打印出應用CPU占用率信息
2、篩選CPU占用率的數(shù)值以及包名
3、把篩選出的數(shù)據(jù)轉換成Excel表格
二、腳本實例
import os
import xlwt
for i in range(5):
val = os.popen(r"adb shell top -d 3 -n 1 | findstr -e +包名 ").read()
f = open(r"C:UsersAdministratorDesktop12321.txt", "a")
result = str(val)
f.write(result)
f.close()
print("ok")
f1 = open(r"C:UsersAdministratorDesktop12321.txt")
for x in f1:
line1 = x.split(' ')[7:8]
line11 = str(line1)[2:4]
line2 = x.split(' ')[-1:]
line22 = str(line2)[2:-4]
result = (line11 +":"+line22) +"n"
f2 = open(r"C:UsersAdministratorDesktop12322.txt", "a")
f2.write(result)
f2.close()
else:
print("Finally finished")
f3 = open(r"C:UsersAdministratorDesktop12322.txt")
workbook = xlwt.Workbook()
sheet = workbook.add_sheet('CPU數(shù)據(jù)', cell_overwrite_ok=True)
sheet.write(0, 1, "包名")
sheet.write(0, 0, "CPU占用率")
x = 1
y = 0
while True:
line3 = f3.readline()
if not line3:
break
for i in line3.split(':'):
item = i.strip()
print(item)
sheet.write(x, y, item)
y += 1
x += 1
y = 0
workbook.save(r'C:UsersAdministratorDesktop12322.xls')
以上就是腳本實例,大家有空可以多多練習。