wxPython制作跑monkey工具(python3)-带显示设备列表界面
一. wxPython制作跑monkey工具(python3)-带显示设备列表界面 源代码 Run Monkey.py
#!/usr/bin/env python import wx
import os
import sys
import time from threading import Thread #执行adb命令函数
#使用到的线程:RunMonkeyThread(),KillMonkeyThread(),ExportLogThread()
def excuOrder(orderName):
c = os.system(orderName) #读取指定文件的指定内容
#使用到的函数getDevices() ,KillMonkeyThread()
def openFile(FileName):
FName = open(FileName, 'r')
fileContent = FName.readlines()
FName.close()
return fileContent #删除列表中指定的元素
#使用的到函数getDevices()
def delElem(delStr,delList):
for i in delList:
if delStr in delList:
delList.remove(delStr) #判断输入的内容是否为数字字符0~
def CheckInput(inputString):
mother = ""
for j in inputString:
if j not in mother:
return None return inputString #获取设备列表
def getDevices():
while(True):
deviceList = []
deviceListRE = []
deviceListLong=
deviceListThird = []
deviceListThirdLong = print ("please run again, if no responsing!")
orderName = "adb devices > device.txt"
excuOrder(orderName)
time.sleep() deviceList=openFile("device.txt") deviceListLong=len(deviceList) #获取列表deviceList长度 if(deviceListLong > ):
for i in range(deviceListLong):
deviceListThird.append(deviceList[i].strip()) delElem("* daemon not running. starting it now on port 5037 *",deviceListThird)
delElem("* daemon started successfully *",deviceListThird)
delElem("List of devices attached",deviceListThird)
delElem("adb server is out of date. killing...",deviceListThird)
delElem("",deviceListThird) #删除deviceListThird列表中的""元素 deviceListThirdLong = len(deviceListThird) if(deviceListThirdLong > ):
for i in range(deviceListLong):
#将deviceList列表中的元素通过空格分隔后赋值给deviceListRE
deviceListRE.append(deviceListThird[i].split("\t")[])
deviceListRE.append(deviceListThird[i].split("\t")[].strip()) deviceListRE=list(set(deviceListRE)) #列表去重,无法保持原有顺序 delElem("device",deviceListRE) #删除deviceListRE列表中"device\n"元素
delElem("offline",deviceListRE) #删除deviceListRE列表中"offline\n"元素
#print(deviceListRE)
return deviceListRE
else:
return ["No Devices!"] #获取应用列表
def getPackages(deviceName):
while(True): packageList=[]
packageListRE=[]
packageListLong= #获取monkey进程
orderName2 = 'adb -s %s shell "touch /sdcard/PackageName.txt"' % deviceName #生成PackageName.txt文件
excuOrder(orderName2)
orderName3 = 'adb -s %s shell "pm list packages >/sdcard/PackageName.txt"' % deviceName #将monkey进程信息放入PackageName.txt文件
excuOrder(orderName3)
time.sleep()
orderName4 = 'adb -s %s pull /sdcard/PackageName.txt .' % deviceName #将PackageName.txt文件到处到当前文件夹
excuOrder(orderName4)
time.sleep()
packageList = openFile("PackageName.txt") #print(packageList) packageListLong=len(packageList) #获取列表packageList长度 for i in range(packageListLong):
#将packageList列表中的元素通过冒号分隔后赋值给 packageListRE
packageListRE.append(packageList[i].split(":")[])
packageListRE.append(packageList[i].split(":")[].strip()) packageListRE=list(set(packageListRE)) #列表去重,无法保持原有顺序 delElem("package",packageListRE) #删除packageListRE列表中package元素 return packageListRE #获取monkeyPID列表
def getMonkeyPID(deviceName): MonkeyPIDList = []
#获取monkey进程
orderName2 = 'adb -s %s shell "touch /sdcard/MonkeyPID.txt"' % deviceName #生成MonkeyPID.txt文件
excuOrder(orderName2)
orderName3 = 'adb -s %s shell "ps|grep monkey >/sdcard/MonkeyPID.txt"' % deviceName #将monkey进程信息放入MonkeyPID.txt文件
excuOrder(orderName3)
orderName4 = 'adb -s %s pull /sdcard/MonkeyPID.txt .' % deviceName #将MonkeyPID.txt文件到处到当前文件夹
excuOrder(orderName4)
MonkeyPIDS = openFile("MonkeyPID.txt")
if(len(MonkeyPIDS)>): #如果存在monkey进程,则提示跑monkey的进程
MonkeyPIDSLong = len(MonkeyPIDS)
for i in range(MonkeyPIDSLong):
#将self.MonkeyPID列表中的元素通过空格分隔后赋值给self.MonkeyPIDRE列表
MonkeyPID = MonkeyPIDS[i].split(" ")
delElem("",MonkeyPID) #删除self.MonkeyPID列表中所有空""项 MonkeyPIDList.append(MonkeyPID[]) return MonkeyPIDList #将指定内容写入指定文件(写入monkey日志报错信息)
#使用到的函数:findException()
def writeFile(FileName, content):
FName = open(FileName, 'a')
FName.write(content)
FName.close() #查找指定文件里指定字符串的个数,并输出字符串所在行的内容
#使用到的线程:ExportLogThread()
def findException(tfile,sstr):
try:
lines=open(tfile,'r').readlines()
flen=len(lines)-
acount =
fileException = "%s_%s" % (tfile,sstr)
tfileException = "%s.txt" % fileException writeFile(tfileException,"%s keywords:\n" % fileException)
for i in range(flen):
if sstr in lines[i]:
lineException = '\t%s\n'% lines[i] writeFile(tfileException,lineException)
acount+= writeFile(tfileException,"%s frequency:%s" % (fileException,acount))
print('Please check Exception keywords in the "%s"\n' % tfileException)
except Exception as e:
print(e) #判断变量输入内容是否为空
#使用到的线程:RunMonkeyThread()
def CheckNone(checkText,discription):
if(checkText == None):
print(discription) class RunMonkeyThread(Thread): def __init__(self):
#线程实例化是立即启动
Thread.__init__(self)
self.logNameST = logNameST
self.MonkeyRunState = MonkeyRunStateText
self.RunMonkeyButton = button1
self.start() def run(self): self.RunMonkeyButton.Enable(False)
self.RunMonkeyButton.SetLabel("Waiting...")
self.DeviceName=DeviceDiaplay.GetStringSelection()
self.packageName=packageText.GetValue()
self.MonkeyTime=MTText.GetValue()
self.MonkeyCount=MCText.GetValue() #获取monkey进程
self.MonkeyPIDList= []
self.MonkeyPIDList = getMonkeyPID(self.DeviceName)
self.MonkeyPIDListLong = len(self.MonkeyPIDList) print("#####",CheckInput(self.MonkeyTime))
print("****",type(CheckInput(self.MonkeyTime)))
print("#####",CheckInput(self.MonkeyCount))
print("****",type(CheckInput(self.MonkeyCount))) if(self.DeviceName == "" or self.DeviceName =="No Devices!"):
self.logNameST.SetLabel("")
self.MonkeyRunState.SetLabel("Not running: Please select the device!")
elif(self.packageName == ""):
self.logNameST.SetLabel("")
self.MonkeyRunState.SetLabel("Not running: Please input the packageName!")
elif(self.packageName not in getPackages(self.DeviceName)):
self.logNameST.SetLabel("")
self.MonkeyRunState.SetLabel("Not running: packageName is not exit!")
elif(self.MonkeyTime == ""):
self.logNameST.SetLabel("")
self.MonkeyRunState.SetLabel("Not running: Please input the MonkeyTime!")
elif(CheckInput(self.MonkeyTime) != self.MonkeyTime):
self.logNameST.SetLabel("")
self.MonkeyRunState.SetLabel("Not running: MonkeyTime must be a positive integer!")
elif(self.MonkeyCount == ""):
self.logNameST.SetLabel("")
self.MonkeyRunState.SetLabel("Not running: Please input the MonkeyCount!")
elif(CheckInput(self.MonkeyCount) != self.MonkeyCount):
self.logNameST.SetLabel("")
self.MonkeyRunState.SetLabel("Not running: MonkeyCount must be a positive integer!")
elif(self.MonkeyPIDListLong == ):
print("Start running monkey ...\n")
self.strTime = time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))
self.logName = '%s_%s_monkey.log'%(self.packageName,self.strTime)
open(r"logname.txt",'w').write(self.logName)
self.MonkeyRunState.SetLabel("Starting monkey ...")
self.logNameST.SetLabel("%s" % self.logName)
self.orderName1='adb -s %s shell "monkey -p %s --throttle %s --ignore-crashes --monitor-native-crashes \
--ignore-security-exceptions --ignore-timeouts --ignore-native-crashes --pct-syskeys\
--pct-nav --pct-majornav --pct-touch --pct-appswitch -v -v -v %s\
> /sdcard/%s&" '% (self.DeviceName,self.packageName,self.MonkeyTime,self.MonkeyCount,self.logName)
excuOrder(self.orderName1)
time.sleep() else:
for i in range(self.MonkeyPIDListLong):
self.MonkeyRunState.SetLabel("Monkey PID: %s is running..." % self.MonkeyPIDList[i])
time.sleep() self.RunMonkeyButton.Enable(True)
self.RunMonkeyButton.SetLabel("Run Monkey") class KillMonkeyThread(Thread): def __init__(self):
#线程实例化时立即启动
Thread.__init__(self)
self.MonkeyRunState = MonkeyRunStateText self.start() def run(self):
self.DeviceName=DeviceDiaplay.GetStringSelection()
self.MonkeyPID=[]
self.MonkeyPIDList = [] if(self.DeviceName == "" or self.DeviceName =="No Devices!"):
self.MonkeyRunState.SetLabel("Kill failed: Please select the device!")
else:
#杀死进程的两种命令
#. ps|grep monkey |awk '{print $2}' |xargs kill -
#. PID=`ps |grep monkey|awk '{print $2}'`;kill - $PID;
#self.orderName2 = 'adb shell "ps|grep monkey |awk \'{print $2}\' |xargs kill -9"'
self.MonkeyPIDList = getMonkeyPID(self.DeviceName)
self.MonkeyPIDListLong = len(self.MonkeyPIDList)
if(self.MonkeyPIDListLong > ):
for i in range(self.MonkeyPIDListLong):
self.orderName5 = 'adb -s %s shell "kill -9 %s"' % (self.DeviceName,self.MonkeyPIDList[i]) #杀死monkey进程
excuOrder(self.orderName5)
self.MonkeyRunState.SetLabel("Monkey PID: %s has been killed" % self.MonkeyPIDList[i]) self.MonkeyRunState.SetLabel("Monkey has been killed.")
else:
self.MonkeyRunState.SetLabel("No monkey is running!") class ExportLogThread(Thread): def __init__(self):
#线程实例化时立即启动
Thread.__init__(self)
self.MonkeyRunState = MonkeyRunStateText
self.start() def run(self):
self.DeviceName=DeviceDiaplay.GetStringSelection()
if(self.DeviceName == "" or self.DeviceName =="No Devices!"):
self.MonkeyRunState.SetLabel("Export failed: Please select the device!") else:
self.logo = os.path.isfile('logname.txt')
self.LogNameList = []
self.MonkeyRunState.SetLabel("Exporting...")
if(self.logo):
self.Logname_file = open('logname.txt','r')
self.Lognames = self.Logname_file.readlines()
self.Logname_file.close()
for self.Logname in self.Lognames:
self.LogNameList = self.Logname.split("_") self.LogFileName = self.LogNameList[] + "_" + self.LogNameList[] self.orderName4 = "adb -s %s pull /sdcard/%s ./MonkeyLog_%s/%s" % (self.DeviceName,self.Logname,self.LogFileName,self.Logname)
excuOrder(self.orderName4) time.sleep()
print (u"Pull %s success!" % self.Logname)
findException("./MonkeyLog_%s/%s" % (self.LogFileName,self.Logname) ,"CRASH" )
findException("./MonkeyLog_%s/%s" % (self.LogFileName,self.Logname) ,"Exception") self.orderName5 = "adb -s %s pull /data/anr/traces.txt ./MonkeyLog_%s/traces.txt" % (self.DeviceName,self.LogFileName)
excuOrder(self.orderName5) self.MonkeyRunState.SetLabel("Export Complete.")
else:
self.MonkeyRunState.SetLabel("Export failed: No monkey has been run!") class InsertFrame(wx.Frame): def __init__(self,parent,id):
wx.Frame.__init__(self,parent,id,title="Run monkey",
pos=wx.DefaultPosition,
size=wx.DefaultSize,style=wx.DEFAULT_FRAME_STYLE,
name="frame") panel = wx.Panel(self,-) #创建画板 #设备列表
DeviceLabel = wx.StaticText(panel, -, "Devices List:")
global DeviceDiaplay
DeviceDiaplay = wx.ComboBox(panel, -, "",
size=(,-),choices=getDevices())
#应用包名
PackageLabel = wx.StaticText(panel, -, "Package name:")
global packageText
packageText = wx.TextCtrl(panel, -, "com.iapppay.pay.v4",
size=(,-))
packageText.SetInsertionPoint() #monkey事件之间的间隔时间(ms)
MTLabel = wx.StaticText(panel, -, "Monkey time:")
global MTText
MTText = wx.TextCtrl(panel, -, "",
size=(,-)) #monkey事件总次数
MCLabel = wx.StaticText(panel, -, "Monkey count:")
global MCText
MCText = wx.TextCtrl(panel, -, "",
size=(,-)) global button1
#点击按钮运行monkey
button1 = wx.Button(panel,label="Run Monkey") #将按钮添加到画板 #杀死monkey
button2 = wx.Button(panel,label="Kill Monkey") #将按钮添加到画板 #导出日志
button3 = wx.Button(panel,label="Export Log") #将按钮添加到画板 #日志名字:
MonkeyLogName = wx.StaticText(panel, -, "Monkey logName:")
global logNameST
logNameST = wx.TextCtrl(panel,-,"",
size=(,-)) #状态显示:
MonkeyRunStateName = wx.StaticText(panel, -, "State display:")
global MonkeyRunStateText
MonkeyRunStateText = wx.TextCtrl(panel,-,"",
size=(,-)) #绑定按钮的单击事件
self.Bind(wx.EVT_BUTTON, self.runMonkey, button1)
self.Bind(wx.EVT_BUTTON, self.killMonkey, button2)
self.Bind(wx.EVT_BUTTON, self.exportLog, button3)
#绑定窗口的关闭事件
self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) sizer = wx.FlexGridSizer(cols=, hgap=, vgap=) #设置总sizer sizerSon1 = wx.FlexGridSizer(cols=, hgap=, vgap=) #设置第一个子sizer
sizerSon1.AddMany([DeviceLabel,DeviceDiaplay,PackageLabel,packageText,MTLabel,
MTText,MCLabel,MCText,MonkeyLogName,logNameST,MonkeyRunStateName,
MonkeyRunStateText]) sizerSon2 = wx.FlexGridSizer(cols=, hgap=, vgap=) #设置第二个字sizer
sizerSon2.AddMany([button1,button2,button3]) sizer.AddMany([sizerSon1,sizerSon2])
panel.SetSizer(sizer) def runMonkey(self, event):
RunMonkeyThread() def killMonkey(self,event):
KillMonkeyThread() def exportLog(self,event):
ExportLogThread() def OnCloseMe(self, event):
self.Close(True) def OnCloseWindow(self,event):
self.Destroy() class App(wx.App): def __init__(self,redirect=True, filename=None):
wx.App.__init__(self,redirect,filename) def OnInit(self):
print("Program Startup:")
self.frame = InsertFrame(parent=None,id=-) #创建框架
self.frame.Show()
self.SetTopWindow(self.frame)
#print(sys.stderr) #输出到stderr
return True def OnExit(self):
print("Program running complete.")
return True if __name__=="__main__":
app = App(redirect=False) #.文本重定向从这开始
app.MainLoop()
wxPython制作跑monkey工具(python3)-带显示设备列表界面的更多相关文章
- wxPython制作跑monkey工具(python3)
一. wxPython制作跑monkey工具python文件源代码内容Run Monkey.py如下: #!/usr/bin/env python import wx import os import ...
- wxPython制作跑monkey工具(python3)-带事件百分比显示界面
一. wxPython制作跑monkey工具(python3)-带事件百分比显示界面 源代码 Run Monkey.py #!/usr/bin/env python import wx import ...
- 解决Genymotion无法创建新设备或无法显示设备列表问题
准备工作: 链接: https://pan.baidu.com/s/1i5v4IBN 密码: jc3m 用2.8的和最新VirtualBox-5.1.10-112026-Win 注意事项: 1.笔记本 ...
- JEECG开发第一个菜单显示设备列表
一.新建设备表(t_base_device) ; -- ---------------------------- -- Table structure for t_base_device -- --- ...
- monkeyrunner工具同Monkey工具的差别
Monkey: Monkey工具直接运行在设备或模拟器的adb shell中,生成用户或系统的伪随机事件流. monkeyrunner: monkeyrunner工具则是在工作站上通过API定义的特定 ...
- python制作命令行工具——fire
python制作命令行工具--fire 前言 本篇教程的目的是希望大家可以通读完此篇之后,可以使用python制作一款符合自己需求的linux工具. 本教程使用的是google开源的python第三方 ...
- Monkey工具使用详解
上节中介绍了Monkey工具使用环境的搭建,传送门..本节我将详细介绍Monkey工具的使用. 一.Monkey测试简介 Monkey测试是Android平台自动化的一种手段,通过Monkey程序模拟 ...
- Android压力测试快速入门教程(图解)——Monkey工具
文章目录: 一.Monkey简介 二.Monkey的基本用法 三.Monkey测试示例图解 四.Monkey命令参数介绍 五.Monkey log分析 一.Monkey简介 Monkey:Androi ...
- 阿里UX矢量图标库–最强大的矢量图标库(Icon font制作力荐工具)
继前面介绍过ICON-FONT的制作后,找了几个ICON库都是国外的今天偶然发现阿里巴巴的图标矢量库,www.iconfont.cn用了之后感觉很强大,丰富的图标库(集合阿里妈妈&淘宝的图标库 ...
随机推荐
- URL组成部分详解
URL组成部分详解 URL是Uniform Resource Locator的简写,统一资源定位符. 一个URL是由以下几部分组成的: scheme://host:port/path/?query-s ...
- 【转】Binlog 基本操作
MySQL的二进制日志可以说是MySQL最重要的日志了,它记录了所有的DDL和DML(除了数据查询语句)语句,以事件形式记录,还包含语句所执行的消耗的时间,MySQL的二进制日志是事务安全型的. 一般 ...
- ES5和ES6那些你必须知道的事儿(三)
ES5和ES6那些你必须知道的事儿 ES6新增的东西 一.块级作用域:关键字let,常量const let与var的区别: a.不会进行变量声明提升 b.变量不允许被重复定义 c.变量不允许被删除 d ...
- JavaScript 进制转换
//十进制转其他 var x=111; alert(x.toString(8)); alert(x.toString(16)); //其他转十进制 var x='112'; alert(parseIn ...
- hdu1256
画横线总是一个字符粗,竖线随着总高度每增长6而增加1个字符宽.当总高度从5增加到6时,其竖线宽度从1增长到2.下圈高度不小于上圈高度,但应尽量接近上圈高度,且下圈的内径呈正方形.每画一个"8 ...
- node遍历文件夹并读取文件内容
var fs = require('fs'); var path = require('path');//解析需要遍历的文件夹 var filePath = path.resolve('./dist' ...
- Java 有一对兔子,从出生后第3个月起每个月都生一对兔子,小兔子长到第三个月后每个月又生一对兔子,假如兔子都不死,问每个月的兔子总数为多少?
import java.util.Scanner; /** *有一对兔子,从出生后第3个月起每个月都生一对兔子, *小兔子长到第三个月后每个月又生一对兔子,假如兔子 *都不死,问每个月的兔子总数为多少 ...
- selenium自动化实例: 多层框架中关于iframe的定位,以及select下拉框选择
对于一个自动化的初学者来说会很常见的遇到元素明明存在却始终定位不到, 从而导致脚本报错,当然定位不到元素的原因很多, 其中一种就是多层框架iframe导致的 下方截图示意: 下方为写脚本时候的示例并其 ...
- SpringBoot配置ActiveMQ
1.添加依赖 <!-- activeMQ --> <dependency> <groupId>org.springframework.boot</groupI ...
- Python输入数组(一维数组、二维数组)
一维数组: arr = input("") //输入一个一维数组,每个数之间使空格隔开 num = [int(n) for n in arr.split()] //将输入每个数以空 ...