一、前置说明
在自动化时,经常需要使用命令行工具与系统进行交互,因此可以使用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