获取进程ID指令
adb shell ps | grep packagename
获取进程ID流量
adb shell cat /proc/pid/net/dev
import csv
import os
import string
import time
class Controller():
def __init__(self,count):
#定义测试的次数
self.count = count
self.alldata = [("timestamp","traffic")]
#单次测试过程
def testprocess(self):
#执行获取进程的命令
result = os.popen("adb shell ps | grep com.android.browser")
#进程ID
pid = result.readlines()[0].split(" ")[5]
#获取进程ID使用的流量
traffic = os.popen("adb shell cat /proc/"+pid + "/net/dev")
for line in traffic:
if "etho" in line :
#将所有空行换成#
line = "#".join(line.split())
#按#号拆分,获取收到的和发出的流量
receive = line.split("#")[9]
elif "etho1" in line:
#将所有空行换成#
line= "#",join(line.split())
#按#号拆分,获取收到的的流量
receive = line.split("#")[1]
transmit = line.split("#")[9]
#计算所有的流量之和
alltraffic = string.atoi(receive) + string.atoi(transmit) + string.atoi(receive) + string.atoi(transmit)
#用KB计算流量
alltraffic = alltraffic / 1024
#获取当前时间
cuttenttime = self.getcurrenttime()
#将获取到的数据存入CSV
self.alldata.append((currenttime,alltraffic))
def run (self):
while self.count > 0:
self.testprocess()
self.counter = self.counter - 1
time.sleep(5)
#获取当前时间
def getcurrenttime(self):
time = time.strftime("%Y-%-%m %H:%M:%S")
return time
#存储数据
def SaveDataCsv(self) :
csvfile = file("flow.csv","wb")
writer = csvfile.writer(csvfile)
writer.writerows(self.alldata)
csvfile.close()