logo

该视频仅会员有权观看

立即开通课程「Python 入门」权限。

¥
199
/ 年

美化输出结果(实战)

上面我们已经实现了任务执行引擎,运行代码后输出结果比较简单,我们可以通过格式化输出来使其更加美观,下面我们在 ExecutionEngine 中实现一个格式化输出函数,用于输出任务执行结果。

def calculate_max_width(self): task_headers = [f"TASK [{task.name}]" for task in self.tasks.values()] # play_headers = [f"PLAY [{host.address}]" for host in self.hosts] # recap_header = "PLAY RECAP" # all_headers = task_headers + play_headers + [recap_header] all_headers = task_headers max_header_length = max(len(header) for header in all_headers) max_width = max_header_length + 50 return max_width def format_output(self, host: Host, task: Task, max_width: int): status = "ok" if task.status == "success" else "failed" header_length = max_width - len(f"TASK [{task.name}]") header = f"TASK [{task.name}] {'*' * header_length}" result = f"{status}: [{host.address}]\n" if task.result["stdout"]: result += f"stdout:\n{task.result['stdout']}" if task.result["stderr"]: result += f"stderr:\n{task.result['stderr']}" return f"{header}\n{result}"

上面代码中首先根据任务的状态来判断任务是否执行成功,然后根据任务的结果来输出输出和错误信息,最后将结果格式化输出。另外我们还定义了一个 calculate_max_width 函数,用于计算输出 * 的最大宽度,这样可以使输出结果更加美观。

然后将 run 方法中的输出改为调用这个函数,代码如下:

def run(self): """执行任务""" max_width = self.calculate_max_width() with ThreadPoolExecutor() as executor: futures: list[Future[Any]] = [] for host in self.hosts: for task in self.tasks: future = executor.submit(self._execute_task, host, task) futures.append(future) for future in futures: # 等待任务执行完成 host, task = future.result() # 打印格式化的输出 print(self.format_output(host, task, max_width))

这样我们就可以更加清晰的输出任务执行结果了,运行代码,就可以看到美观的输出结果了。

TASK [List all files in the home directory] ********************************** ok: [master] stdout: total 15928 -rw-r--r-- 1 root root 7214 Feb 22 11:21 Clusterfile -rw-r--r-- 1 root root 96 Mar 9 07:32 config.yaml -rw-r--r-- 1 root root 1466 Mar 17 06:17 cr-demo.yaml -rw-r--r-- 1 root root 186 Mar 17 06:18 crd-demo.yaml -rw-r--r-- 1 root root 16132298 Feb 21 20:34 helm-v3.14.2-linux-amd64.tar.gz -rw-r--r-- 1 root root 1205 Mar 2 08:25 mysql.yaml drwxr-xr-x 10 root root 4096 Mar 2 03:40 nfs-subdir-external-provisioner -rw-r--r-- 1 root root 257 Mar 2 08:07 pdb.yaml -rw-r--r-- 1 root root 21 Aug 14 08:16 remote_file.txt -rw-r--r-- 1 root root 398 Mar 2 07:10 wd1-svc.yaml -rw-r--r-- 1 root root 1641 Mar 2 07:03 wd1.yaml -rw-r--r-- 1 root root 122850 Mar 9 06:25 wget-log -rw-r--r-- 1 root root 2360 Mar 2 08:22 wordpress-v2.yaml -rw-r--r-- 1 root root 1476 Mar 2 07:39 wordpress.yaml TASK [Create a new directory] ************************************************ failed: [master] stderr: mkdir: cannot create directory ‘/tmp/ansible’: File exists TASK [List all files in the home directory] ********************************** ok: [node1] stdout: total 0 TASK [Create a new directory] ************************************************ failed: [node1] stderr: mkdir: cannot create directory ‘/tmp/ansible’: File exists All tasks have been executed.