• python批量安装apk


     目的:节省apk安装花费时间

    #! Python3
    # -- coding: utf-8 --
    import datetime
    import os
    import re
    import subprocess
    from concurrent.futures import ThreadPoolExecutor, as_completed
    
    seq = '-' * 30
    
    
    def get_devices_list():
        """获取设备列表"""
        cmd = ['exit']
        try:
            obj = subprocess.Popen('adb devices', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                                   stderr=subprocess.PIPE)
            tup = obj.communicate((''.join(cmd) + "
    ").encode('utf-8'))
            lists_info = ''.encode('utf-8').join(tup).decode('utf-8').rstrip().splitlines()
            lists_info.pop(0)
            for i in lists_info:
                if 'offline' in i:
                    lists_info.remove(i)
            lists = [x.split('	')[0] for x in lists_info]
            if not lists:
                return '未连接设备'
            else:
                return lists
        except Exception as e:
            return e
    
    
    def device_install_app(device, app_path):
        """安装单个apk"""
        try:
            install_cmd = f'adb -s {device} install -r -t {app_path}'
            result = subprocess.Popen(install_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            global status
            status = False
            for i in result.stdout.readlines():
                if 'Success' in i.decode('utf-8').strip():
                    status = True
            return status, device, app_path
        except Exception as err:
            return err
    
    
    def device_install_apps(device, filenames):
        """批量安装apk"""
        try:
            start = datetime.datetime.now()
            out_result = {}
            success = []
            error = []
            log = []
            t_exec = ThreadPoolExecutor(max_workers=4)
            tasks = [t_exec.submit(device_install_app, device, app_path) for app_path in filenames]
            for feature in as_completed(tasks):
                global status
                status, device, app_path = feature.result()
                app_path_list = re.findall('(.*?).apk', os.path.basename(app_path))
                if status:
                    success.append(app_path_list)
                elif not status:
                    error.append(app_path_list)
                log.append(success)
                log.append(error)
                out_result.update({device: log})
                t_exec.shutdown()
                result = ''
                for k, v in out_result.items():
                    st, er = v
                    s = '' if not st else '
    '.join(x[0] for x in st)
                    e = '' if not er else '
    '.join(y[0] for y in er)
                    result += f'{k}
    成功:
    {s}
    失败:
    {e}
    '
                end = datetime.datetime.now()
                return f'{result}耗时:{(end - start).seconds} 秒
    '
        except Exception as err:
            return err
    
    
    def devices_install_apps(filenames):
        """多设备批量安装apk"""
        try:
            if not filenames:
                return '待安装apk为空'
            devices_result = ''
            devices_list = get_devices_list()
            t_exec = ThreadPoolExecutor(max_workers=50)
            tasks = [t_exec.submit(device_install_apps, device, filenames) for device in devices_list]
            for future in as_completed(tasks):
                fu_result = future.result()
                devices_result += f'{fu_result}{seq}
    '
            t_exec.shutdown()
            return devices_result
        except Exception as e:
            return e
    
    
    path = [r"C:Users..student_ui-debug.apk"]
    print(devices_install_apps(path))

    执行效果:

    S161001002c
    成功:
    student_ui-debug
    失败:
    无
    耗时:11------------------------------
    SX12456893n
    成功:
    student_ui-debug
    失败:
    无
    耗时:11------------------------------

    每次安装改apk地址,若觉得麻烦,可起一个gui界面,如:

    path = (title='安装APP', filetypes=[('apk文件', '*.apk')], initialdir=os.getcwd())

  • 相关阅读:
    反转链表
    Kafka设计解析
    kafka丢失和重复消费数据
    阿里巴巴分布式数据库服务DRDS研发历程
    ZooKeeper系列文章
    阿里中间件RocketMQ
    Spring Cloud构建微服务架构
    TDDL调研笔记
    从OutStreamWriter 和Filewriter谈Java编码
    在Service里调用AlertDialog
  • 原文地址:https://www.cnblogs.com/qianmaoliugou/p/15109001.html
Copyright © 2020-2023  润新知