一、前置說明
在自動化過程中,經常需要在命令行中執行一些操作,比如啟動應用、查殺應用等,因此可以封裝成一個CommandExecutor來專門處理這些事情。
二、操作步驟
# cmd_util.pyimport logging
import os
import platform
import shutil
import subprocessimport psutillogger = logging.getLogger(__name__)class CommandExecutor:@staticmethoddef 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)@classmethoddef 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:passelse: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 logginglogging.basicConfig(level=logging.DEBUG)print(cmd.kill_processes_with_name('夜神'))
歡迎技術交流: