引言
在實際運維、測試、數據分析、開發流程中,我們經常會處理成百上千條命令操作,例如:
各種腳本任務(啟動、備份、重啟、日志查看)
數據處理流程(爬取 → 清洗 → 統計 → 可視化)
配置自動化(環境部署、參數變更)
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