Snake's Home

cmd中之行adb 

在用python编写脚本对android操作时,有时需要通过cmd命令直接对app操作。这样的好处是,如果你想对一页界面操作,不用一步一步的进行界面跳转,可以从主界面一下子调到你想要操作的界面。
通过os.popen()方法打开一个cmd命令

1、os.popen(“adb wait-for devices”):等待连接设备

2、os.popen(“adb shell screencap -p /data/local/tmp.png”):截屏后将图片以.png格式放在 /data/local/文件夹下

3、os.popen(“adb shell pull /data/local/“ +PATH(path+”/“ +timestamp + “.png”)):将手机/data/local/文件夹下文件传到手机文件夹下,并对图片以当时时间命名

4、os.popen(“adb shell am start -n com.xxx.xxx/com.xxx.xxx.plugins.PluginCenterActicity”):直接跳转并打开com.xxx.xxx下的com.xxx.xxx.plugins.PluginCenterActicity界面

下边是手机截屏并上传到电脑中的代码:

#!/usr/bin/pyton
#encoding=utf-8
import time
import sys
import os


timestamp = time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime(time.time()))

type = """
    1. screenshot
    2. logcat
    3. tracefile
    4. device information
"""
print type
yourtype = raw_input("Please choose type: ")

def getlogcat():
        path = os.getcwd()+"/output/logcat"
        if not os.path.isdir(path):
            os.makedirs(path)
        logcatname=path+"/"+timestamp+r"logcat.log"
        cmdlogcat="adb logcat -d >%s" %(logcatname)  
        os.popen(cmdlogcat)   

def gettracefile():  
        path = os.getcwd()+"/output/trace"
        if not os.path.isdir(path):
            os.makedirs(path)
        tracename = path+"/"+timestamp+r"trace.log"
        cmd="adb shell cat /data/anr/traces.txt>%s" %(tracename)
        os.popen(cmd) 

def screenshot():
        path = os.getcwd()+"/output/pic"
        if not os.path.isdir(path):
            os.makedirs(path)


        os.popen("adb shell screencap -p /sdcard/monkey_run.png")

        cmd="adb pull /sdcard/monkey_run.png %s" %(path)
        os.popen(cmd)  
        os.popen("adb shell rm /sdcard/monkey_run.png")
        oldname = path+"/" + "monkey_run.png"
        newname= path+"/" + timestamp +r".png"
        os.rename(oldname, newname)

        print "success"

def getdeviceinfo():
        cmd = 'adb shell cat /system/build.prop'
        deviceinfo = os.popen(cmd)
        infoList = deviceinfo.readlines()
        #print infoList

        dict ={}

        param = ['ro.product.manufacturer','ro.build.version.release','ro.build.version.sdk','ro.product.model','ro.product.brand','ro.product.locale.language','ro.product.locale.region']

        for info in infoList:
            for each_param in param:
                if str(each_param) in str(info):
                    k = info.split('=')[0]
                    s = k.split('.')
                    dict[s[-1]] = info.split('=')[1].strip()
        print dict.items()


deviceText = os.popen('adb devices')
textList = deviceText.readlines()
deviceName = textList[1].split()[0]

if deviceName == '':
    print "please connect devices!"

else:

    if yourtype == '1':
        screenshot()

    if yourtype == '2':
        getlogcat()

    if yourtype == '3':
        gettracefile()

    if yourtype == '4':
        getdeviceinfo()