常用办公脚本工具

1 前言

​ 本文基于 Android 自动化测试项目adb常用命令总结,整理了一些常用办公脚本,后续会根据工作需求持续更新。

​ 脚本资源见→常用办公脚本工具

​ 脚本目录如下:

img

  • base:基础工具包
  • apply:具体应用场景

​ 注意:对于 apply 目录下所有文件的文件名,必须能在 phone.py 中找到同名的方法,init.py 是一个空的文件(用于解决 ModuleNotFoundError 报错问题)。

​ 用户在安装 python 解释器并配置好环境变量后,只需单击 apply 里面的 bat 文件,即可获取需要的信息,如:清除当前打开 app 的缓存数据、获取当前打开 app 的安装包、获取当前打开 app 的 paclage 和 activity、截屏、截虚拟屏、获取最近截屏或录屏文件等。

2 脚本

2.1 基础脚本

​ phone.py

import subprocess as sp
import re
import os
 
# 手机类(封装了对手机的操作)
class Phone:
    # 初始化(connect:连接类型)
    def __init__(self, connect_type="usb"):
        self.get_device_id(connect_type)
        self.model = self.get_phone_model()
        self.size = self.get_phone_size()
        self.vs_display_id = self.get_vs_display_id()
        global bat_path
        bat_path = os.path.abspath(os.path.abspath(os.path.dirname(__file__)) + "\\..\\apply") + "\\"
 
    # 获取设备 id(connect_type:连接类型)
    def get_device_id(self, connect_type="usb"):
        if connect_type == "usb":
            self.id = self.get_device_id_by_usb()  # 通过 usb 连接设备
        elif connect_type == "wifi":
            self.ip = self.get_device_id_by_wifi()  # 通过 wifi 连接设备
 
    # 通过 usb 连接获取设备id(程序运行期间需要保持有线连接)
    def get_device_id_by_usb(self):
        rst = sp.check_output('adb devices')
        id = re.findall("[A-Z0-9]{12,16}", str(rst))[0]
        return id
 
    # 通过 wifi 连接获取设备id(程序启动时需要有线连接,运行后可以断开数据线)
    def get_device_id_by_wifi(self):
        rst = sp.check_output('adb shell \"ip addr | grep global\"')
        ip = re.findall("\d+.\d+.\d+.\d+", str(rst))[0]
        return ip
 
    # 获取手机型号
    def get_phone_model(self):
        rst = sp.check_output('adb shell getprop ro.product.model')
        model = re.findall("\w+-?\w+", str(rst))[0]
        print(model)
        return model
 
    # 获取手机分辨率
    def get_phone_size(self):
        rst = sp.check_output('adb shell wm size')
        str_size = re.findall("\d+", str(rst))
        x = eval(str_size[0])
        y = eval(str_size[1])
        return (x, y)
 
    # 获取 visual display id
    def get_vs_display_id(self):
        rst = sp.check_output('adb shell dumpsys activity activities')
        displays = re.findall("Display #\d+", str(rst))
        vs_id = -1
        for e in displays:
            id = eval(re.findall("\d+", e)[0])
            if id > 0:
                vs_id = id
                break
        return vs_id
 
    # 截手机屏
    def _2_screenshot(self):
        src_path = str(self.get_root_path()) + "/1.png"
        des_path = bat_path + "phone.png"
        os.system("adb shell screencap -p " + src_path)
        os.system("adb pull " + src_path + " " + des_path)
 
    # 截虚拟屏
    def _3_screenshot_vs(self):
        if self.vs_display_id > 0:
            src_path = str(self.get_root_path()) + "/1.png"
            dest_path = bat_path + "vs_" + str(self.vs_display_id) + ".png"
            os.system("adb shell screencap -d " + str(self.vs_display_id) + " -p " + src_path)
            os.system("adb pull " + src_path + " " + des_path)
        else:
            print("Visual display does not exist")
 
    # 获取当前应用的 package 和 Activity
    def _1_get_pkg_activity(self):
        rst = sp.check_output('adb shell dumpsys window | grep "mCurrentFocus"')
        win = re.findall("\{.+\}", str(rst))[0]
        activity = win.replace("}", "").split(" ")[-1]
        pkg = activity.split("/")[0]
        print("package:", pkg)
        print("activity:", activity)
        return [pkg, activity]
 
    # 获取当前应用的安装路径
    def get_install_path(self):
        pkg, activity = self._1_get_pkg_activity()
        rst = sp.check_output('adb shell pm path ' + pkg)
        path = str(rst).split(":")[1].split("\\")[0]
        print("path:", path)
        return path
 
    # 获取当前应用的 apk
    def _6_get_apk(self):
        path = self.get_install_path()
        os.system("adb pull "+ path + " " + bat_path)
 
    # 清除当前应用的缓存数据
    def _5_clear_app_data(self):
        pkg, activity = self._1_get_pkg_activity()
        os.system("adb shell pm clear "+ pkg)

    # 获取最近一次截屏或录屏文件
    def _4_get_last_shot(self):
        path1 = str(self.get_root_path()) + "/Pictures/Screenshots/"
        file1 = self.get_last_file(path1)
        path2 = str(self.get_root_path()) + "/Movies/Screenrecords/"
        file2 = self.get_last_file(path2)
        path = ""
        if len(file1) > 0:
            path = file1[1]
        if len(file2) > 0 and (len(path) == 0 or file2[0] > file1[0]):
            path = file2[1]
        if len(path) > 0:
            print("path: " + path)
            os.system("adb pull " + path)

    # 获取最近一次截屏或录屏文件的时间和路径
    def get_last_file(self, path):
        files_list = self.get_files_list(path)
        files = []
        for file in files_list:
            temp = file.split(" ")
            if temp[-1] == "." or temp[-1] == ".." or temp[0][0] == "d":
                continue
            files += [temp[-4] + "_" + temp[-3], temp[-1]]
        if len(files) == 0:
            print("there is no file in " + path)
            return []
        last_time = files[0]
        last_file = files[1]
        for i in range(2, len(files), 2):
            if files[i] > last_time:
                last_time = files[i]
                last_file = files[i+1]
        print("last_time: " + last_time + ", last_file: " + last_file)
        return [last_time, path + last_file]

    # 获取存储根路径
    def get_root_path(self):
        try:
            rst = sp.check_output("adb shell cd sdcard")
            return "/sdcard"
        except sp.CalledProcessError:
            print("sdcard不存在或不是目录, 已切换根目录为: /storage")
            os.system("adb root && adb remount")
            return "/storage"

    # 获取路径中文件列表
    def get_files_list(self, path):
        try:
            rst = sp.check_output("adb shell ls -all " + path)
            files_list = str(rst).split("\\r\\n")[1:-1]
            return files_list
        except sp.CalledProcessError:
            return []

​ 说明:Phone 类中封装了对手机的操作,如:获取安装包、截屏、清应用数据、获取最近一次截屏或录屏文件等。

​ invoke.py

# 将项目根目录添加到系统路径中,防止在命令行运行此脚本时,报错:
# ModuleNotFoundError: No module named 'py_script'
import os
import sys
root_path = screen_shot_path = os.path.abspath(os.path.abspath(os.path.dirname(__file__)) + "\\..")
sys.path.append(root_path)

# 通过反射调用 Phone 的方法
from base.phone import Phone
ph = Phone()
if hasattr(ph, sys.argv[1]):
    fun = getattr(ph, sys.argv[1])
    fun()
else:
    print("This method does not exist in Phoen ", sys.argv[1])

​ 说明:sys.argv 指从命令行中获取的输入参数,如下,sys.argv[1] 指 get_apk。

python invoke.py get_apk

​ transit.bat

@echo off
python ../base/invoke.py %1
pause

​ 说明:transit.bat 用于中转业务脚本的文件名,并回调 invoke.py,“%1” 指 invoke.bat 文件后跟随的第一个参数,如:在命令行输入如下内容,%1 指 get_pkg_activity。

transit.bat get_pkg_activity

2.2 应用

1)获取 package 和 activity

​ get_pkg_activity.bat

../base/transit.bat %~n0

​ 说明:“%~n0” 指当前文件名,即“get_pkg_activity”。

2)获取 apk

​ get_apk.bat

../base/transit.bat %~n0

3)清除应用缓存

​ clear_app_data.bat

../base/transit.bat %~n0

4)截手机屏

​ screenshot.bat

../base/transit.bat %~n0

5)截虚拟屏

​ screenshot_vs.bat

../base/transit.bat %~n0

6)获取最近截图或录屏

​ get_last_shot.bat

../base/transit.bat %~n0

​ 声明:本文转自常用办公脚本工具

posted @   little_fat_sheep  阅读(91)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
点击右上角即可分享
微信分享提示