【自动化测试】【安卓android】python 发送adb命令方法

2023-05-16

#command 命令列表,可以传入任意命令,类型为list
#cmdMode可以选择发送命令方式为直接发送adb 命令还是先进入shell
    def sendAdbcmd(command, deviceID="", cmdMode="cmd", sleepTime=1,timeout=20,returnType="string"):
        res = ""
        contextlist = []
        try:
            if cmdMode == 'cmd':
                # 依次执行命令
                cmdFinal = ""
                for cmdComand in command:
                    cmdFinal = cmdFinal + cmdComand + '&'
                f = os.popen(cmdFinal)
                #print("发送命令为:%s" % cmdFinal)
                if sleepTime != 0:
                    sleep(sleepTime)
                contextlist = f.readlines()
                if contextlist != []:
                    pass
                    #print("打印命令返回结果%s" % str(contextlist))
                f.close()
            elif cmdMode == 'shell':
                if "exit" not in command:
                    command.append("exit")
                    command.append("exit")
                obj = subprocess.Popen('adb -s %s shell' % deviceID, stdin=subprocess.PIPE,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE, shell=True)
                context, syserr = obj.communicate(("\n".join(command) + "\n").encode(),timeout=timeout)
                contextlist = str(context).split('\\r')
                if contextlist != []:
                    pass
                    #print("打印命令返回结果%s" % contextlist)

            if returnType == "list":
                return contextlist
            else:
                for con in contextlist:
                    for c in command:
                        if c in con:
                            try:
                                contextlist.remove(con)
                            except:
                                pass

                for con in contextlist:
                    if con != "":
                        res = res + con.lstrip("'b").replace('\r', "").replace('\n', "").strip(" ")

        except Exception as e:
            logging.info("adb 命令发送失败,失败原因%s" % e)
            return res
        else:
            return res

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【自动化测试】【安卓android】python 发送adb命令方法 的相关文章

随机推荐