Python Appium Selenium 查杀进程的实用方法

简介: Python Appium Selenium 查杀进程的实用方法

一、前置说明


在自动化过程中,经常需要在命令行中执行一些操作,比如启动应用、查杀应用等,因此可以封装成一个CommandExecutor来专门处理这些事情。


二、操作步骤


# cmd_util.py
import logging
import os
import platform
import shutil
import subprocess
import psutil
logger = logging.getLogger(__name__)
class CommandExecutor:
    @staticmethod
    def execute_command(command):
        """
        subprocess.run() 方法用于执行命令并等待其完成,然后返回一个 CompletedProcess 对象,该对象包含执行结果的属性。
        它适用于需要等待命令完成并获取结果的情况。
        """
        try:
            result = subprocess.run(command, shell=True, capture_output=True, text=True)
            if result.returncode == 0:
                return result.stdout.strip()
            else:
                return result.stderr.strip()
        except Exception as e:
            return str(e)
    @classmethod
    def kill_processes_with_name(cls, name):
        """
        查杀窗口名称包含 name 的所有进程,支持模拟匹配
        """
        try:
            if platform.system() == 'Windows':
                # Windows系统使用tasklist和findstr命令来获取包含特定字符串的窗口进程列表
                command = f'tasklist /V /FO CSV | findstr /C:"{name}"'
                output = cls.execute_command(command)
                if output:
                    # 遍历输出的进程列表
                    for line in output.splitlines():
                        # 解析进程信息
                        process_info = line.split(",")
                        process_name = process_info[0].strip('"')
                        process_id = process_info[1].strip('"')
                        # 先尝试关父进程,解决:关掉uiautomatorview或appium server 之后, 会留下一个无用的cmd的窗口
                        try:
                            # 获取父进程
                            parent_process = psutil.Process(int(process_id)).parent()
                            # 终止父进程(CMD窗口)
                            kill_parent_command = f"taskkill /F /T /PID {parent_process.pid}"
                            cls.execute_command(kill_parent_command)
                        except:
                            pass
                        # 如果没有父进程,则直接关闭子进程;如果父进程已关闭,子进程会消失,也try catch 一下
                        try:
                            # 终止进程
                            kill_command = f"taskkill /F /T /PID {process_id}"
                            cls.execute_command(kill_command)
                            # 记录日志
                            logger.info(f"Stopped process '{process_name}' with ID '{process_id}'")
                        except:
                            pass
                else:
                    logger.info(f"No processes found with window name containing '{name}'")
            else:
                # 其他操作系统使用wmctrl命令获取包含特定字符串的窗口列表
                command = f"wmctrl -l | grep {name}"
                window_list = cls.execute_command(command)
                if window_list:
                    # 遍历输出的窗口列表
                    for line in window_list.splitlines():
                        # 解析窗口信息
                        window_info = line.split()
                        window_id = window_info[0]
                        # 关闭窗口
                        os.system(f"wmctrl -ic {window_id}")
                    # 记录日志
                    logger.info(f"Stopped processes with window name containing '{name}'")
                else:
                    logger.info(f"No processes found with window name containing '{name}'")
        except Exception as e:
            logger.warning(f"Error: {str(e)}")
cmd_executor = CommandExecutor()
cmd = cmd_executor


三、Demo验证


以关闭多开的两个夜神模拟器,来测试代码,顺利关闭:

if __name__ == '__main__':
    import logging
    logging.basicConfig(level=logging.DEBUG)
    print(cmd.kill_processes_with_name('夜神'))


目录
相关文章
|
11月前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
666 1
|
12月前
|
机器学习/深度学习 数据采集 数据挖掘
基于 GARCH -LSTM 模型的混合方法进行时间序列预测研究(Python代码实现)
基于 GARCH -LSTM 模型的混合方法进行时间序列预测研究(Python代码实现)
418 2
|
调度 Python
微电网两阶段鲁棒优化经济调度方法(Python代码实现)
微电网两阶段鲁棒优化经济调度方法(Python代码实现)
292 0
|
传感器 大数据 API
Python数字限制在指定范围内:方法与实践
在Python编程中,限制数字范围是常见需求,如游戏属性控制、金融计算和数据过滤等场景。本文介绍了五种主流方法:基础条件判断、数学运算、装饰器模式、类封装及NumPy数组处理,分别适用于不同复杂度和性能要求的场景。每种方法均有示例代码和适用情况说明,帮助开发者根据实际需求选择最优方案。
552 0
Python字符串center()方法详解 - 实现字符串居中对齐的完整指南
Python的`center()`方法用于将字符串居中,并通过指定宽度和填充字符美化输出格式,常用于文本对齐、标题及表格设计。
|
11月前
|
人工智能 数据安全/隐私保护 异构计算
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
1683 8
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
|
11月前
|
SQL 测试技术 数据库
healenium+python+selenium
上次介绍了如何利用healenium+java+selenium来实现selenium的自愈,这次介绍如何healenium+python+selenium。关于healenium+python+selenium网上资料更少,并且甚至是错误的。在著名的书籍《软件测试权威指南中》也是有一定问题的。现在介绍如下
521 4
|
机器学习/深度学习 数据采集 算法
【CNN-BiLSTM-attention】基于高斯混合模型聚类的风电场短期功率预测方法(Python&matlab代码实现)
【CNN-BiLSTM-attention】基于高斯混合模型聚类的风电场短期功率预测方法(Python&matlab代码实现)
556 4
|
11月前
|
算法 调度 决策智能
【两阶段鲁棒优化】利用列-约束生成方法求解两阶段鲁棒优化问题(Python代码实现)
【两阶段鲁棒优化】利用列-约束生成方法求解两阶段鲁棒优化问题(Python代码实现)
326 0
|
12月前
|
机器学习/深度学习 数据采集 TensorFlow
基于CNN-GRU-Attention混合神经网络的负荷预测方法(Python代码实现)
基于CNN-GRU-Attention混合神经网络的负荷预测方法(Python代码实现)
635 0

推荐镜像

更多