Best Python code snippet using uiautomator
am.py
Source:am.py  
1#!/usr/bin/env python32# -*- coding: utf-8 -*-3# ////////////////////////////////////////////////////////////////////4# 5# The Android Debug Bridge Wrapper Project by Python6# 7# @Author Mr.Shouheng8# 9# @References:10# - https://developer.android.com/studio/command-line/adb?hl=zh-cn#am11# 12# ////////////////////////////////////////////////////////////////////13import logging14from time import sleep15from typing import List16from adb import *17import sys18sys.path.insert(0, '../')19import global_config20class ProcessInfo:21    '''Process information wrapper object.'''22    def __init__(self, pro: str, pid: str):23        self.pro = pro24        self.pid = pid25    def __str__(self) -> str:26        return "%s(%s)" % (self.pro, self.pid)27def stop_app_by_package_name(pkg: str, serial: str = None) -> bool:28    '''Stop App of given package name.'''29    return os_system("adb %s shell am force-stop %s ", serial, pkg) == 030def get_launcher_of_package_name(pkg: str, serial: str = None) -> str:31    '''Get launcher class of given package name.'''32    out = os_popen("adb %s shell dumpsys package %s ", serial, pkg)33    index = out.find('Category: "android.intent.category.LAUNCHER"')34    part = out[0:index]35    s_index = part.rfind(pkg)36    part = part[s_index:index]37    e_index = part.find(' ')38    launcher = part[0:e_index]39    return launcher40def start_app_by_package_name(pkg: str, serial: str = None) -> bool:41    '''Start App by launcher class.'''42    launcher = get_launcher_of_package_name(pkg, serial)43    return os_system("adb %s shell am start %s ", serial, launcher) == 044def restart_app_by_package_with_profiling(pkg: str, file: str, serial: str = None) -> int:45    '''Restart APP with given package name.'''46    stop_app_by_package_name(pkg, serial)47    launcher = get_launcher_of_package_name(pkg, serial)48    ret = os_popen("adb %s shell am start -n %s --start-profiler %s --sampling %s ", serial, launcher, file, '10')49    logging.debug("Start info: " + ret)50    return 151def stop_profiler_and_download_trace_file(pkg: str, file: str, to: str, serial: str = None) -> int:52    '''Stop profiler and download the trace file to local.'''53    pros = get_processes_of_pcakage_name(pkg, serial)54    logging.debug("Try to kill process : " + str(pros[0]))55    out = os_popen("adb %s shell am profile stop %s ", serial, pros[0].pid)56    logging.debug("Stop profiler: " + out)57    sleep(10) # Delays for few seconds, currently may writing to the profiler file. (It's emprt now.)58    ret = pull(file, to, serial)59    logging.debug("Pull file from %s to %s : %s" % (file, to, str(ret)))60    return ret61def restart_app_by_with_profiling_and_duration(pkg: str, to: str, duration: int, serial: str = None) -> int:62    '''63    Restart APP and profiler by package name.64    - pkg:      package name65    - to:       local file path to store the profiler file66    - duration: the time duration to collect the profiler data67    '''68    smapling_file = "/data/local/tmp/temp_sampling.trace"69    restart_app_by_package_with_profiling(pkg, smapling_file, serial)70    sleep(duration)71    return stop_profiler_and_download_trace_file(pkg, smapling_file, to, serial)72def dumpheap_by_package(pkg: str, to: str, serial: str = None) -> int:73    '''Dumpheap of given package.'''74    pros = get_processes_of_pcakage_name(pkg, serial)75    temp = "/data/local/tmp/temp.heap"76    if len(pros) == 0:77        return -178    logging.debug("Try to dump process : " + str(pros[0]))79    os_system("adb %s shell am dumpheap %s %s ", serial, pros[0].pid, temp)80    return pull(temp, to, serial) 81def dumpheap_by_package(pkg: str, process_name: str, to: str, serial: str = None) -> int:82    '''Dumpheap of given package.'''83    pros = get_processes_of_pcakage_name(pkg, serial)84    temp = "/data/local/tmp/temp.heap"85    if len(pros) == 0:86        return -187    pro = pros[0]88    for p in pros:89        if p == process_name:90            pro = p91    logging.debug("Try to dump process : " + str(pro))92    os_system("adb %s shell am dumpheap %s %s ", serial, pro.pid, temp)   93    return pull(temp, to, serial)94def restart_app_by_package_name(pkg: str, serial: str = None) -> bool:95    '''Restart App by package name.'''96    stop_app_by_package_name(pkg, serial)97    return start_app_by_package_name(pkg, serial)98def get_processes_of_pcakage_name(pkg: str, serial: str = None) -> List[ProcessInfo]:99    '''Get all processes info of package name.'''100    processes = []101    # The 'awk' command is invlaid on adb shell, so it will take into effect.102    text = os_popen("adb %s shell \"ps -ef|grep %s|grep -v grep| awk \'{print $1}\'\"", serial, pkg)103    lines = [line.strip() for line in text.split('\n')]104    for line in lines:105        parts = [col.strip() for col in line.split(' ')]106        cols = []107        for part in parts:108            if part != '':109                cols.append(part)110        if len(cols) == 0:111            continue112        pid = cols[1]113        pro = cols[7].removeprefix(pkg)114        if pro == '':115            pro = ':main'116        process = ProcessInfo(pro, pid)117        processes.append(process)118    return processes119def get_top_activity_info(serial: str = None) -> str:120    '''Get top activities info.'''121    return os_popen("adb %s shell dumpsys activity top", serial)122def capture_screen(to: str, serial: str = None) -> int:123    '''Capture screen.'''124    temp = "/sdcard/screen.png"125    os_system("adb %s shell screencap %s ", serial, temp)126    return pull(temp, to, serial)127if __name__ == "__main__":128    global_config.config_logging('../log/app.log')129    TEST_PACKAGE_NAME = ""130    TEST_DEVICE_SERIAL = "emulator-5556"131    TEST_APK_PATH = "/Users/wangshouheng/downloads/Snapdrop-0.3.apk"132    TEST_LOCAL_FILE = "adb.py"133    TEST_REMOTE_DIR = "/sdcard"134    TEST_REMOTE_FILE = "/sdcard/adb.py"135    # stop_app_by_package_name(TEST_PACKAGE_NAME)136    # stop_app_by_package_name(TEST_PACKAGE_NAME, TEST_DEVICE_SERIAL)137    # print(get_launcher_of_package_name(TEST_PACKAGE_NAME))138    # print(get_launcher_of_package_name(TEST_PACKAGE_NAME, TEST_DEVICE_SERIAL))139    # print(start_app_by_package_name(TEST_PACKAGE_NAME))140    # print(start_app_by_package_name(TEST_PACKAGE_NAME, TEST_DEVICE_SERIAL))141    # print_list(get_processes_of_pcakage_name(TEST_PACKAGE_NAME))142    # print_list(get_processes_of_pcakage_name(TEST_PACKAGE_NAME, TEST_DEVICE_SERIAL))143    # print(get_top_activity_info())144    # print(get_top_activity_info(TEST_DEVICE_SERIAL))145    # os_system("adb %s shell am > ./am.md", TEST_DEVICE_SERIAL)146    # restart_app_by_with_profiling_and_duration(TEST_PACKAGE_NAME, "~/desktop/sampling.trace", 6, TEST_DEVICE_SERIAL)147    # dumpheap_by_package(TEST_PACKAGE_NAME, ":main", "~/desktop/file.heap", TEST_DEVICE_SERIAL)...adb.py
Source:adb.py  
1#!/usr/bin/env python32# -*- coding: utf-8 -*-3import os4from typing import List5# ////////////////////////////////////////////////////////////////////6# 7# The Android Debug Bridge Wrapper Project by Python8# 9# @Author Mr.Shouheng10# 11# @References:12# - https://developer.android.com/studio/command-line/adb?hl=zh-cn#am13# 14# ////////////////////////////////////////////////////////////////////15class DeviceInfo:16    '''Adb attached device info.'''17    def __init__(self) -> None:18        self.infos = []19    def append(self, info: str):20        '''Append one info to infos.'''21        self.infos.append(info)22    def __str__(self) -> str:23        ret = ''24        for info in self.infos:25            ret = ret + info + '\n'26        return ret27def get_devices() -> List[DeviceInfo]:28    '''Get all attached devices.'''29    text = os_popen("adb devices -l", None)30    lines = [line.strip() for line in text.split('\n')]31    devices = []32    for line in lines[1:]:33        parts = [part.strip() for part in line.split(' ')]34        device = DeviceInfo()35        index = 036        for part in parts:37            if len(part) > 0:38                index = index+139                if index == 1:40                    device.append("serial:" + part)41                elif index == 2:42                    device.append("state:" + part)43                else:44                    device.append(part)45        devices.append(device)46    return devices47def get_version() -> List[str]:48    '''Get adb version info.'''49    text = os_popen("adb version", None)50    lines = [line.strip() for line in text.split('\n')]51    return lines52def reboot(serial: str = None) -> int:53    '''Reboot device.'''54    return os_system("adb %s reboot ", serial)55def export_bugreport(path: str, serial: str = None) -> int:56    '''Export bugreport, ANR log etc.'''57    return os_system("adb %s bugreport %s", serial, path)58def install(apk: str, serial: str = None) -> int:59    '''60    Install given package:61    - apk: path of APK.62    '''63    return os_system("adb %s install %s ", serial, apk)64def uninstall(pkg: str, keep: bool, serial: str = None) -> bool:65    '''66    Uninstall given package.67    - pkg: package name68    - keep: keep the data and cache directories if true, otherwise false.69    '''70    if keep:71        return os_system("adb %s uninstall -k %s ", serial, pkg) == 072    else:73        return os_system("adb %s uninstall %s ", serial, pkg) == 074def push(local: str, remote: str, serial: str = None) -> int:75    '''76    Push local file to remote directory.77    - local: local file path78    - remote: the remote path to push to79    '''80    return os_system("adb %s push %s %s", serial, local, remote)81def pull(remote: str, local: str, serial: str = None) -> int:82    '''83    Pull file from remote phone:84    - remote: remote file path85    - local: local to store file86    '''87    return os_system("adb %s pull %s %s", serial, remote, local)88def os_system(command: str, serial: str, *args) -> int:89    '''Execute command by os.system().'''90    f_args = []91    if serial is None:92        f_args.append(" ")93    else:94        f_args.append(" -s %s " % serial)95    f_args.extend(args)96    if len(f_args) == 1 and f_args[0] == " ":97        return os.system(command)98    return os.system(command % tuple(f_args))99def os_popen(command: str, serial: str, *args) -> str:100    '''Execute command by os.popen().'''101    f_args = []102    if serial is None:103        f_args.append(" ")104    else:105        f_args.append(" -s %s " % serial)106    f_args.extend(args)107    if len(f_args) == 1 and f_args[0] == " ":108        out = os.popen(command)109    else:110        out = os.popen(command % tuple(f_args))111    return out.read().strip()112def print_list(list: List):113    '''Print list.'''114    for item in list:115        print(str(item) + ", ")116if __name__ == "__main__":117    TEST_PACKAGE_NAME = "me.shouheng.leafnote"118    TEST_DEVICE_SERIAL = "emulator-5556"119    TEST_APK_PATH = "/Users/wangshouheng/downloads/Snapdrop-0.3.apk"120    TEST_LOCAL_FILE = "adb.py"121    TEST_REMOTE_DIR = "/sdcard"122    TEST_REMOTE_FILE = "/sdcard/adb.py"123    # print_list(get_devices())124    # print(get_version())125    # print(reboot())126    # print(reboot(TEST_DEVICE_SERIAL))127    # print(export_bugreport('~/bugs'))128    # print(export_bugreport('~/bugs', TEST_DEVICE_SERIAL))129    # print(uninstall(TEST_PACKAGE_NAME, False))130    # print(uninstall(TEST_PACKAGE_NAME, False, TEST_DEVICE_SERIAL))131    # print(install(TEST_APK_PATH))132    # print(install(TEST_APK_PATH, TEST_DEVICE_SERIAL))133    # print(os_system("ls -al " + TEST_APK_PATH, None))134    # print(push(TEST_LOCAL_FILE, TEST_REMOTE_DIR, TEST_DEVICE_SERIAL))135    # print(pull(TEST_REMOTE_FILE, "~", TEST_DEVICE_SERIAL))136    # os_system("a", "b", "c", "d", "e")...pm.py
Source:pm.py  
1#!/usr/bin/env python32# -*- coding: utf-8 -*-3# ////////////////////////////////////////////////////////////////////4# 5# The Android Debug Bridge Wrapper Project by Python6# 7# @Author Mr.Shouheng8# 9# @References:10# - https://developer.android.com/studio/command-line/adb?hl=zh-cn#am11# 12# ////////////////////////////////////////////////////////////////////13from adb import *14from typing import List15class PackageInfo:16    def __init__(self, pkg: str = '', path: str = '', uid: str = '', vcode: str = '') -> None:17        self.pkg = pkg18        self.path = path19        self.uid = uid20        self.vcode = vcode21    22    def __str__(self) -> str:23        return "(%s, %s, %s, %s)" % (self.pkg, self.path, self.uid, self.vcode)24def get_packages(serial: str = None) -> List[PackageInfo]:25    '''Get all packages'''26    out = os_popen("adb %s shell pm list packages -f -U -u --show-versioncode ", serial)27    infos = []28    for line in out.split("\n"):29        info = _parse_package_line(line)30        infos.append(info)31    return infos32def get_package_info(pkg: str, serial: str = None) -> PackageInfo:33    '''Get info of one package.'''34    out = os_popen("adb %s shell pm list packages -f -U -u --show-versioncode | grep %s ", serial, pkg)35    return _parse_package_line(out)36def download_apk_of_package(pkg: str, to: str, serial: str = None) -> int:37    '''Download APK of given package name to given path.'''38    info = get_package_info(pkg, serial)39    if len(info.path) > 0:40        return pull(info.path, to, serial)41    return -142def _parse_package_line(line: str) -> PackageInfo:43    '''Parse package info from line text.'''44    parts = line.split(" ")45    info = PackageInfo()46    for part in parts:47        if len(part) > 0:48            pairs = part.split(":")49            if len(pairs) >= 2:50                if pairs[0] == "package":51                    index = pairs[1].rindex("=")52                    info.path = pairs[1][0:index]53                    info.pkg = pairs[1][index+1:]54                elif pairs[0] == "versionCode":55                    info.vcode = pairs[1]56                elif pairs[0] == "uid":57                    info.uid = pairs[1]58    return info59if __name__ == "__main__":60    TEST_PACKAGE_NAME = "me.shouheng.leafnote"61    TEST_DEVICE_SERIAL = "emulator-5556"62    TEST_APK_PATH = "/Users/wangshouheng/downloads/Snapdrop-0.3.apk"63    TEST_LOCAL_FILE = "adb.py"64    TEST_REMOTE_DIR = "/sdcard"65    TEST_REMOTE_FILE = "/sdcard/adb.py"66    # print_list(get_packages(TEST_DEVICE_SERIAL))67    # print(get_package_info(TEST_PACKAGE_NAME, TEST_DEVICE_SERIAL))68    print(download_apk_of_package(TEST_PACKAGE_NAME, "~/leafnote.apk", TEST_DEVICE_SERIAL))...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
