引言
在实际运维、测试、数据分析、开发流程中,我们经常会处理成百上千条命令操作,例如:
各种脚本任务(启动、备份、重启、日志查看)
数据处理流程(爬取 → 清洗 → 统计 → 可视化)
配置自动化(环境部署、参数变更)
Git 操作(拉取、推送、合并、冲突处理)
如何高效组织这些操作?传统做法如 bash 脚本 or Makefile
存在诸多限制:
难以组织、无分组、查找不便
不支持搜索/筛选/分页交互
缺乏状态反馈、没有界面结构感
因此我们构建一个 终端交互式命令管理面板,支持以下特性:
✅ 分组展示命令(如 dev、deploy、git)
✅ 支持分页与快速搜索
✅ 高亮显示当前项、运行状态反馈
✅ 一键执行 / 复制命令
✅ 支持配置文件导入、自动补全
一、功能目标
模块 | 说明 |
---|---|
分组管理 | 支持多个命令组和命令项定义 |
搜索过滤 | 可输入关键字过滤显示项 |
高亮互动 | 上下移动 / 分页浏览 / 回车执行 |
状态输出 | 显示执行状态(成功/失败) |
数据持久 | 配置文件支持 JSON / YAML / TOML |
扩展能力 | 适配各类 CLI/SSH/脚本调度命令 |
二、技术栈
库 | 用途 |
---|---|
textual | 基于 rich 的 TUI(终端 UI)框架 |
subprocess | 执行外部命令并捕获输出 |
pyperclip | 复制命令到剪贴板(可选) |
yaml/json | 命令配置支持 |
threading/asyncio | 支持命令异步执行反馈 |
安装依赖
bash
复制编辑
pip install textual rich pyperclip pyyaml
三、项目结构
bash
复制编辑
cli_dashboard/ ├── main.py # 启动入口 ├── config.yaml # 命令配置文件 ├── dashboard.py # UI 面板主逻辑 ├── executor.py # 命令执行器 └── utils.py # 通用函数
四、配置文件 config.yaml
yaml
复制编辑
groups: - name: DevOps commands: - name: 启动服务 command: "python run.py" - name: 重启服务 command: "systemctl restart myapp" - name: Git 管理 commands: - name: 拉取更新 command: "git pull" - name: 查看日志 command: "git log --oneline" - name: 数据处理 commands: - name: 运行分析脚本 command: "python analysis.py"
五、命令执行模块 executor.py
python
复制编辑
import subprocess def execute(cmd): try: result = subprocess.run(cmd, shell=True, capture_output=True, text=True) if result.returncode == 0: return (True, result.stdout.strip()) else: return (False, result.stderr.strip()) except Exception as e: return (False, str(e))
六、UI 面板主逻辑 dashboard.py
我们使用 textual
构建界面:
python
复制编辑
from textual.app import App, ComposeResult from textual.widgets import Header, Footer, Static, Input, ListView, ListItem from textual.containers import Vertical import yaml from executor import execute class CommandPanel(App): CSS_PATH = "styles.css" def __init__(self, config_file="config.yaml"): super().__init__() self.config_file = config_file self.all_items = [] self.filtered_items = [] def compose(self) -> ComposeResult: yield Header() yield Input(placeholder="🔍 输入关键字过滤命令", id="search") yield ListView(id="cmdlist") yield Static(id="output") yield Footer() def on_mount(self): self.load_commands() def load_commands(self): with open(self.config_file, "r", encoding="utf-8") as f: data = yaml.safe_load(f) for group in data.get("groups", []): gname = group.get("name") for cmd in group.get("commands", []): label = f"[bold]{gname}[/] · {cmd['name']}" self.all_items.append({"label": label, "cmd": cmd["command"]}) self.query_one("#cmdlist").clear() for item in self.all_items: self.query_one("#cmdlist").append(ListItem(Static(item["label"]))) def on_input_changed(self, event: Input.Changed): keyword = event.value.strip().lower() listbox = self.query_one("#cmdlist") listbox.clear() for item in self.all_items: if keyword in item["label"].lower(): listbox.append(ListItem(Static(item["label"]))) def on_list_view_selected(self, event: ListView.Selected): idx = event.index cmd = self.all_items[idx]["cmd"] self.query_one("#output").update(f"[green]运行中:[/] {cmd}") success, output = execute(cmd) if success: self.query_one("#output").update(f"[bold green]✅ 执行成功:[/]\n{output}") else: self.query_one("#output").update(f"[bold red]❌ 执行失败:[/]\n{output}")
七、程序入口 main.py
python
复制编辑
from dashboard import CommandPanel if __name__ == "__main__": CommandPanel().run()
八、运行效果展示
启动项目:
bash
复制编辑
python main.py
界面效果:
csharp
复制编辑
┌────────────────────────────────────────────┐ │ CLI 插件命令面板(分组展示) │ ├────────────────────────────────────────────┤ │ 🔍 输入关键字过滤命令:python │ │ │ │ ▸ DevOps · 启动服务 │ │ DevOps · 重启服务 │ │ Git 管理 · 拉取更新 │ │ 数据处理 · 运行分析脚本 │ │ │ ├────────────────────────────────────────────┤ │ ✅ 执行成功: │ │ ... output from subprocess here ... │ └────────────────────────────────────────────┘
支持方向键切换命令、回车执行,输出实时更新。
九、功能增强建议
功能模块 | 说明 |
---|---|
命令分组折叠 | 支持点击分组展开/折叠命令 |
命令参数输入 | 每条命令支持动态参数填写 |
执行日志记录 | 自动记录运行成功/失败与时间戳 |
图标/emoji 支持 | 命令项支持展示图标(如 🚀、🗂) |
多配置文件切换 | 支持 --config 切换配置源 |
插件任务扩展 | 与实际脚本、远程 SSH、API 联动 |
十、适用场景
场景 | 应用价值 |
---|---|
运维脚本统一入口 | 跨环境部署、服务控制集中管理 |
数据开发流程管理 | 数据提取、模型更新、清洗绘图流程集中调用 |
Git 团队操作面板 | 常见分支、拉取、提交命令快速执行 |
教学示范 | 帮助学生理解多命令流程、结构化运行 |
十一、总结
本项目构建了一个终端交互式命令控制面板,具备:
✅ 分组展示结构清晰
✅ 搜索高效,适合命令量大的项目
✅ 回车执行、状态输出一目了然
✅ 基于配置即可扩展命令项,无需修改主逻辑
你可以将它用于运维面板、部署入口、教学工具,甚至打包为私有命令中心平台。
bbs.yantuchina.com/read.php?tid=339663
bbs.yantuchina.com/read.php?tid=339664
learnku.com/articles/90356