一. 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)-带显示设备列表界面的更多相关文章

  1. wxPython制作跑monkey工具(python3)

    一. wxPython制作跑monkey工具python文件源代码内容Run Monkey.py如下: #!/usr/bin/env python import wx import os import ...

  2. wxPython制作跑monkey工具(python3)-带事件百分比显示界面

    一. wxPython制作跑monkey工具(python3)-带事件百分比显示界面  源代码 Run Monkey.py #!/usr/bin/env python import wx import ...

  3. 解决Genymotion无法创建新设备或无法显示设备列表问题

    准备工作: 链接: https://pan.baidu.com/s/1i5v4IBN 密码: jc3m 用2.8的和最新VirtualBox-5.1.10-112026-Win 注意事项: 1.笔记本 ...

  4. JEECG开发第一个菜单显示设备列表

    一.新建设备表(t_base_device) ; -- ---------------------------- -- Table structure for t_base_device -- --- ...

  5. monkeyrunner工具同Monkey工具的差别

    Monkey: Monkey工具直接运行在设备或模拟器的adb shell中,生成用户或系统的伪随机事件流. monkeyrunner: monkeyrunner工具则是在工作站上通过API定义的特定 ...

  6. python制作命令行工具——fire

    python制作命令行工具--fire 前言 本篇教程的目的是希望大家可以通读完此篇之后,可以使用python制作一款符合自己需求的linux工具. 本教程使用的是google开源的python第三方 ...

  7. Monkey工具使用详解

    上节中介绍了Monkey工具使用环境的搭建,传送门..本节我将详细介绍Monkey工具的使用. 一.Monkey测试简介 Monkey测试是Android平台自动化的一种手段,通过Monkey程序模拟 ...

  8. Android压力测试快速入门教程(图解)——Monkey工具

    文章目录: 一.Monkey简介 二.Monkey的基本用法 三.Monkey测试示例图解 四.Monkey命令参数介绍 五.Monkey log分析 一.Monkey简介 Monkey:Androi ...

  9. 阿里UX矢量图标库–最强大的矢量图标库(Icon font制作力荐工具)

    继前面介绍过ICON-FONT的制作后,找了几个ICON库都是国外的今天偶然发现阿里巴巴的图标矢量库,www.iconfont.cn用了之后感觉很强大,丰富的图标库(集合阿里妈妈&淘宝的图标库 ...

随机推荐

  1. 如何将baseUrl项目地址提取放到放到static

    原本项目的baseUrl地址是放在src/common/config.js ,但是这有一个缺点,就是本地测试一个地址,生产一个地址.每发一次不同環境的包就要build一下,太麻烦了!有没有解决的办法呢 ...

  2. JRebel springboot部署idea

    JRebel springboot部署idea     http://127.0.0.1:8888/88414687-3b91-4286-89ba-2dc813b107ce   ctrl+shift+ ...

  3. SharePoint CU、Hotfix和SP版本的区别

    1.Hotfix:通常是对一个特殊问题的修复包 2.CU(Cumulative Update):Hotfix的集合,包含从上一个SP(Service Pack)版本以来所有的Hotfix 3.SP(S ...

  4. GIT 初始化 中文编码、自动换行

    解决中文编码: git config --global core.quotepath false git config --global gui.encoding utf-8 解决git log 中文 ...

  5. ubuntu16.04安装pycharm

    Ubuntu16.04下,默认安装了python2.7和python3.5,在终端下,输入“Python”  或“python3”可查看具体版本. 1.安装PyCharm前,先配置PyCharm的JD ...

  6. 前端车牌识别SDK算法提取

    同行业中,别人标配有的产品我有,别人没有的产品我们也有,如此才能增强竞争力,通过优化创新,前端车牌识别SDK功能,性能上,都是行业NO.1的水平.车牌识别sdk这个用于越来越多人集成了,汽车保有量日益 ...

  7. react系列笔记:第一记-redux

    前言: 目前公司使用dva,对于前不久还是使用原生js的我来说,花了差不多一两周时间,基本掌握如何使用.虽然对于react有一点点基础,但很多地方未深入,很多概念也很模糊,故从本文开始,记录一下系统的 ...

  8. 转载: http状态码

    消息   这一类型的状态码,代表请求已被接受,需要继续处理.这类响应是临时响应,只包含状态行和某些可选的响应头信息,并以空行结束.由于 HTTP/1.0 协议中没有定义任何 1xx 状态码,所以除非在 ...

  9. C语言的#if #ifdef #ifndef

    #if #ifedf #ifndef   —般情况下,C语言源程序中的每一行代码.都要参加编译.但有时候出于对程序代码优化的考虑.希望只对其中一部分内容进行编译.此时就需要在程序中加上条件,让编译器只 ...

  10. DevExpress ASP.NET Core Controls 2019发展蓝图(No.1)

    本文主要为大家介绍DevExpress ASP.NET Core Controls2019年的官方发展蓝图,更多精彩内容欢迎持续收藏关注哦~ [DevExpress ASP.NET Controls ...