一、前置说明
在自动化时,经常需要使用命令行工具与系统进行交互,因此可以使用python封装一个执行cmd命令的方法。
二、代码实现
import subprocess
import timefrom common.exception import RunCMDError
from common.logger import loggerclass CmdRunner:@staticmethoddef run_command(command, timeout=5, retry_interval=0.5):end_time = time.time() + timeoutattempts = 0while True:try:# subprocess.run() 方法用于执行命令并等待其完成,然后返回一个 CompletedProcess 对象,该对象包含执行结果的属性。# 它适用于需要等待命令完成并获取结果的情况。result = subprocess.run(command, shell=True, capture_output=True, text=True, timeout=timeout)# 如果 returncode==0,则直接returnif result.returncode == 0:# 通常情况下,执行成功时,命令行不会返回任何结果,此时result为'',因此添加这个判断output = result.stdout.strip() or 'successful'logger.debug(f"Execute adb command successfully: {command}")output, status = output, Truereturn output, status# 如果 returncode!=0 或 抛出异常时,则进入失败重跑。# 连续执行多条语句时,cmd命令之间需要一定时间间隔,失败重跑的机制,就是为了避免执行速度过快导致的错误。else:logger.error(f"Execute adb command failure: {command}")output, status = result.stderr.strip(), Falseexcept Exception as e:logger.error(f"Execute adb command failure: {e}")output, status = '', Falsetime.sleep(retry_interval)attempts += 1logger.debug(f'Retrying... Attempt {attempts}')if time.time() > end_time:breakreturn output, statusdef run_command_strict(self, command, timeout=5):output, status = self.run_command(command, timeout=timeout)if not status:raise RunCMDError(output)return outputcmd_runner = CmdRunner()if __name__ == '__main__':import logginglogging.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
欢迎技术交流: