如何将ping函数输出显示在npyscreen的SERVER盒子组件中?
解决npyscreen中自定义ping函数输出破坏布局的问题
你的核心问题是直接使用print输出结果,绕过了npyscreen的终端渲染系统,导致布局混乱。需要修改代码让ping结果通过npyscreen组件展示,同时适配其颜色机制。
修改后的完整代码
#!/usr/bin/env python # encoding: utf-8 import sys import curses import npyscreen import os from os import name, system hostnames = ["1.1.1.1", "0.0.0.0", "2.2.2.2"] class Column(npyscreen.BoxTitle): _contained_widget = npyscreen.MultiLine def resize(self): self.max_height = int(0.73 * terminal_dimensions()[0]) def terminal_dimensions(): return curses.initscr().getmaxyx() def ping(): results = [] for host in hostnames: # 执行ping命令,静默输出 response = os.system(f"ping -c 1 {host} > /dev/null 2>&1") if response == 0: results.append((f" {host}", 'GOOD')) else: results.append((f" {host}", 'BAD')) return results class dashboard(npyscreen.NPSApp): def main(self): # 初始化自定义颜色对 curses.init_pair(1, curses.COLOR_GREEN, curses.COLOR_BLACK) curses.init_pair(2, curses.COLOR_RED, curses.COLOR_BLACK) F = npyscreen.Form(name="DASHBOARD") widget_top = F.add( Column, name="SERVER", relx=2, rely=2, max_width=40, ) # 获取ping结果并填充到组件 ping_results = ping() widget_top.values = [text for text, _ in ping_results] # 为每行设置对应颜色 for idx, (_, status) in enumerate(ping_results): color_pair = curses.color_pair(1) if status == 'GOOD' else curses.color_pair(2) widget_top.entry_widget.lineColors[idx] = color_pair F.edit() def clear(): if name == 'nt': _ = system('cls') else: _ = system('clear') if __name__ == "__main__": clear() App = dashboard() App.run()
关键修改说明
- 替换ANSI颜色为curses颜色对:npyscreen基于curses库,不支持终端ANSI转义码,改用
curses.init_pair定义颜色组合,通过lineColors为每行绑定对应颜色。 - 重构ping函数返回结果列表:不再直接打印结果,而是将主机状态文本和状态标识存入列表返回,让npyscreen组件统一处理输出。
- 移除全局print调用:所有内容都通过npyscreen的组件展示,避免直接操作终端破坏布局。
内容的提问来源于stack exchange,提问作者0x01_PH
相关产品推荐
相关产品推荐

