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
目录
相关文章
|
5天前
|
C++ 开发者 Python
实现Python日志点击跳转到代码位置的方法
本文介绍了如何在Python日志中实现点击跳转到代码位置的功能,以提升调试效率。通过结合`logging`模块的`findCaller()`方法记录代码位置信息,并使用支持点击跳转的日志查看工具(如VS Code、PyCharm),开发者可以从日志直接点击链接定位到出错代码,加快问题排查。
14 2
|
5天前
|
索引 Python
Python 中寻找列表最大值位置的方法
本文介绍了Python中找列表最大值及其位置的三种方法:1) 使用内置`max()`和`index()`函数;2) 通过循环遍历;3) 利用`enumerate()`函数和生成器表达式。每种方法均附有示例代码,其中`enumerate()`方法在保证效率的同时代码更简洁。
31 2
|
5天前
|
JSON 数据处理 数据格式
Python中批量提取[]括号内第一个元素的四种方法
Python中批量提取[]括号内第一个元素的四种方法
23 1
|
5天前
|
SQL 关系型数据库 数据库连接
使用 Python 访问数据库的基本方法
【5月更文挑战第12天】在Python中操作数据库涉及安装数据库驱动(如mysql-connector-python, psycopg2, pymongo)、连接数据库、执行查询/更新、处理结果集及关闭连接。使用ORM(如SQLAlchemy)可简化操作。通过上下文管理器(with语句)能更好地管理资源和错误。注意根据实际需求处理事务、错误和安全性,例如使用SSL连接。
23 2
|
5天前
|
Linux Shell Python
python实现Tree命令输出
python实现Tree命令输出
7 0
|
5天前
|
测试技术 开发者 Python
Python检查函数和方法的输入/输出
【5月更文挑战第5天】Python检查函数和方法的输入/输出
15 1
|
5天前
|
Python
【Python进阶(四)】——魔术命令
【Python进阶(四)】——魔术命令
|
5天前
|
Python
【Python进阶(二)】——程序调试方法
【Python进阶(二)】——程序调试方法
|
5天前
|
存储 Linux Shell
python移除/删除非空文件夹/目录的最有效方法是什么?
python移除/删除非空文件夹/目录的最有效方法是什么?
11 0
|
5天前
|
Linux 数据安全/隐私保护 iOS开发
如何将python命令链接到Python3
如何将python命令链接到Python3
13 0