python封装执行cmd命令的方法

简介: python封装执行cmd命令的方法

一、前置说明


在自动化时,经常需要使用命令行工具与系统进行交互,因此可以使用python封装一个执行cmd命令的方法。


二、代码实现


import subprocess
import time
from common.exception import RunCMDError
from common.logger import logger
class CmdRunner:
    @staticmethod
    def run_command(command, timeout=5, retry_interval=0.5):
        end_time = time.time() + timeout
        attempts = 0
        while True:
            try:
                # subprocess.run() 方法用于执行命令并等待其完成,然后返回一个 CompletedProcess 对象,该对象包含执行结果的属性。
                # 它适用于需要等待命令完成并获取结果的情况。
                result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=timeout)
                # 如果 returncode==0,则直接return
                if result.returncode == 0:
                    # 通常情况下,执行成功时,命令行不会返回任何结果,此时result为'',因此添加这个判断
                    output = result.stdout.strip() or 'successful'
                    logger.debug(f"Execute adb command successfully: {command}")
                    output, status = output, True
                    return output, status
                # 如果 returncode!=0 或 抛出异常时,则进入失败重跑。
                # 连续执行多条语句时,cmd命令之间需要一定时间间隔,失败重跑的机制,就是为了避免执行速度过快导致的错误。
                else:
                    logger.error(f"Execute adb command failure: {command}")
                    output, status = result.stderr.strip(), False
            except Exception as e:
                logger.error(f"Execute adb command failure: {e}")
                output, status = '', False
            time.sleep(retry_interval)
            attempts += 1
            logger.debug(f'Retrying... Attempt {attempts}')
            if time.time() > end_time:
                break
        return output, status
    def run_command_strict(self, command, timeout=5):
        output, status = self.run_command(command, timeout=timeout)
        if not status:
            raise RunCMDError(output)
        return output
cmd_runner = CmdRunner()
if __name__ == '__main__':
    import logging
    logging.basicConfig(level=logging.DEBUG)
    print(cmd_runner.run_command_strict('adb devices'))


三、Demo验证


运行代码,输出结果:

Execute adb command successfully: adb devices
List of devices attached
9YS0220306003185  device
192.168.2.103:5555  device
目录
相关文章
|
9月前
|
测试技术 开发者 Python
Python单元测试入门:3个核心断言方法,帮你快速定位代码bug
本文介绍Python单元测试基础,详解`unittest`框架中的三大核心断言方法:`assertEqual`验证值相等,`assertTrue`和`assertFalse`判断条件真假。通过实例演示其用法,帮助开发者自动化检测代码逻辑,提升测试效率与可靠性。
592 1
|
10月前
|
机器学习/深度学习 数据采集 数据挖掘
基于 GARCH -LSTM 模型的混合方法进行时间序列预测研究(Python代码实现)
基于 GARCH -LSTM 模型的混合方法进行时间序列预测研究(Python代码实现)
348 2
|
10月前
|
调度 Python
微电网两阶段鲁棒优化经济调度方法(Python代码实现)
微电网两阶段鲁棒优化经济调度方法(Python代码实现)
255 0
|
9月前
|
人工智能 数据安全/隐私保护 异构计算
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
1451 8
桌面版exe安装和Python命令行安装2种方法详细讲解图片去水印AI源码私有化部署Lama-Cleaner安装使用方法-优雅草卓伊凡
|
10月前
|
机器学习/深度学习 数据采集 算法
【CNN-BiLSTM-attention】基于高斯混合模型聚类的风电场短期功率预测方法(Python&matlab代码实现)
【CNN-BiLSTM-attention】基于高斯混合模型聚类的风电场短期功率预测方法(Python&matlab代码实现)
488 4
|
10月前
|
人工智能 自然语言处理 安全
Python构建MCP服务器:从工具封装到AI集成的全流程实践
MCP协议为AI提供标准化工具调用接口,助力模型高效操作现实世界。
1670 1
|
9月前
|
算法 调度 决策智能
【两阶段鲁棒优化】利用列-约束生成方法求解两阶段鲁棒优化问题(Python代码实现)
【两阶段鲁棒优化】利用列-约束生成方法求解两阶段鲁棒优化问题(Python代码实现)
277 0
|
10月前
|
机器学习/深度学习 数据采集 TensorFlow
基于CNN-GRU-Attention混合神经网络的负荷预测方法(Python代码实现)
基于CNN-GRU-Attention混合神经网络的负荷预测方法(Python代码实现)
545 0
|
9月前
|
数据采集 机器学习/深度学习 人工智能
Python:现代编程的首选语言
Python:现代编程的首选语言
1475 102

推荐镜像

更多