mcpField
P
python-cli-ops

python-cli-ops

github.com/0xdarkmatter开发7851 次安装2 周前更新
代码仓库

关于 python-cli-ops

面向 Python 命令行开发的参考技能,介绍 Typer 与 Rich 的常用模式,并提供模板及专题参考资料。

主要功能

  1. 01Typer 应用与命令组
  2. 02Rich 表格、进度与格式化
  3. 03错误处理模式
  4. 04配置与进阶参考资料
  5. 05可复用的 CLI 应用模板

适用场景

  1. 01启动基于 Typer 的 CLI
  2. 02添加分组命令
  3. 03展示表格和进度
  4. 04查阅配置模式

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/0xdarkmatter/claude-mods --skill python-cli-ops

安装后在 Claude Code 中输入/python-cli-ops确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

assets/
cli-template.py
references/
configuration.md
rich-output.md
typer-patterns.md
scripts/
.gitkeep

详细介绍

Python CLI 模式

使用 Typer 和 Rich 进行现代 CLI 开发。

基本 Typer 应用

import typer

app = typer.Typer(
    name="myapp",
    help="My awesome CLI application",
    add_completion=True,
)

@app.command()
def hello(
    name: str = typer.Argument(..., help="Name to greet"),
    count: int = typer.Option(1, "--count", "-c", help="Times to greet"),
    loud: bool = typer.Option(False, "--loud", "-l", help="Uppercase"),
):
    """Say hello to someone."""
    message = f"Hello, {name}!"
    if loud:
        message = message.upper()
    for _ in range(count):
        typer.echo(message)

if __name__ == "__main__":
    app()

命令组

import typer

app = typer.Typer()
users_app = typer.Typer(help="User management commands")
app.add_typer(users_app, name="users")

@users_app.command("list")
def list_users():
    """List all users."""
    typer.echo("Listing users...")

@users_app.command("create")
def create_user(name: str, email: str):
    """Create a new user."""
    typer.echo(f"Creating user: {name} <{email}>")

@app.command()
def version():
    """Show version."""
    typer.echo("1.0.0")

# Usage: myapp users list
#        myapp users create "John" "[email protected]"
#        myapp version

Rich 输出

from rich.console import Console
from rich.table import Table
from rich.progress import track
from rich.panel import Panel
import typer

console = Console()

@app.command()
def show_users():
    """Display users in a table."""
    table = Table(title="Users")
    table.add_column("ID", style="cyan")
    table.add_column("Name", style="green")
    table.add_column("Email")

    users = [
        (1, "Alice", "[email protected]"),
        (2, "Bob", "[email protected]"),
    ]
    for id, name, email in users:
        table.add_row(str(id), name, email)

    console.print(table)

@app.command()
def process():
    """Process items with progress bar."""
    items = list(range(100))
    for item in track(items, description="Processing..."):
        do_something(item)
    console.print("[green]Done![/green]")

错误处理

import typer
from rich.console import Console

console = Console()

def error(message: str, code: int = 1):
    """Print error and exit."""
    console.print(f"[red]Error:[/red] {message}")
    raise typer.Exit(code)

@app.command()
def process(file: str):
    """Process a file."""
    if not os.path.exists(file):
        error(f"File not found: {file}")

    try:
        result = process_file(file)
        console.print(f"[green]Success:[/green] {result}")
    except ValueError as e:
        error(str(e))

快速参考

功能Typer 语法
必需参数name: str
可选参数name: str = "default"
选项typer.Option(default, "--flag", "-f")
参数typer.Argument(..., help="...")
布尔标志verbose: bool = False
枚举选项color: Color = Color.red
Rich 功能用法
表格Table() + add_column/row
进度track(items)
颜色[red]text[/red]
面板Panel("content", title="Title")

其他资源

  • ./references/typer-patterns.md - 高级 Typer 模式
  • ./references/rich-output.md - Rich 表格、进度和格式设置
  • ./references/configuration.md - 配置文件和环境变量

资源文件

  • ./assets/cli-template.py - 完整的 CLI 应用模板

另请参阅

相关技能:

  • python-typing-ops - CLI 参数的类型提示
  • python-observability-ops - CLI 应用的日志记录

互补技能:

  • python-env - 打包 CLI 以便分发

评论

支持 Markdown