这是monkeyrunner截图限时免费阅读#1的后作.
之前的脚本中将所有的东西都放在主线程里面执行, 实际上, 保存MonkeyImage
到磁盘的过程是IO相当大的, 将这类操作放入单独的线程进行处理能大大提高脚本运行的效率.
我们创建一个线程, 指定一个方法和要传入的参数, 就可以让这个方法在线程中执行, 线程需要是非守护线程, 不过这个是默认的.
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice, MonkeyImage
import sys, os, time, threading
def saveMonkeyImageToFile(img, name):
'''save monkey img to file'''
img.writeToFile(name, "png")
def saveMonkeyImageByThread(img, name):
'''save monkey img to file using thread'''
t = threading.Thread(target=saveMonkeyImageToFile, args=(img, name,))
t.start()
if (__name__ == '__main__'):
PF_PNG = ".png"
PN_WIDTH = "display.width"
PN_HEIGHT = "display.height"
DOWN_AND_UP = "down_and_up"
TARGET_PATH = os.getcwd() + '/freeder' + str(int(round(time.time()*1000))) + '/'
os.mkdir(TARGET_PATH)
print 'create dir: ' + TARGET_PATH
print 'waiting for connection'
device = MonkeyRunner.waitForConnection()
print 'device connected'
touch_x = int(device.getProperty(PN_WIDTH)) - 10
touch_y = int(device.getProperty(PN_HEIGHT)) / 2
page = 1
if (len(sys.argv) == 2):
page = int(sys.argv[1])
old_img = device.takeSnapshot()
while (True):
device.touch(touch_x, touch_y, DOWN_AND_UP)
time.sleep(1)
new_img = device.takeSnapshot()
if (new_img.sameAs(old_img)):
print 'snapshot is same, exit'
break
else:
saveMonkeyImageByThread(old_img, TARGET_PATH + str(page) + PF_PNG)
print 'write image to file, nameing ' + str(page) + '.png'
old_img = new_img
page += 1
print 'done exit'
脚本的主要改动在于将存储图片的过程变为了新建一个线程去处理.