SuperAPI AI 工具集

python3-cli

编程与开发

查看项目

更新于 10-16 15:08

技能介绍

用途

python3-cli 用于指导用 Python 3 构建命令行应用,重点是 Typer 与 Rich 两个库的使用方式,并强调在动手选择展示库之前先识别 CLI 的主要消费方。

受众优先原则

  • 若 CLI 实现在 Agent Skill 或插件内部,默认面向智能体:不要用 Rich 渲染命令输出,应在 stdout 输出紧凑 JSON,最好来自 Pydantic 响应模型并用 model_dump_json() 生成,不做缩进;诊断信息发送到 stderr,并保持 JSON schema 稳定。
  • 面向人类的 CLI 可以使用 Typer + Rich 做终端呈现。
  • 混合受众时,紧凑 JSON 是自动化契约,人类可读格式是显式的展示模式。
  • 智能体不应需要解析表格、颜色、进度条、面板或说明性文字才能消费工具结果。

主要能力与标准

资料列出的标准包括:

  • 所有 CLI 参数使用 Annotated[Type, typer.Option(...)] 语法。
  • 使用 rich_help_panel 对选项分组。
  • 面向人类输出时使用 Rich emoji 记号(如 :white_check_mark:),而非 Unicode 字面量。
  • 架构:CLI → 业务逻辑 → 服务 → 输出边界(面向智能体输出紧凑 JSON,面向人类使用 Rich 显示)。
  • 优先使用 uv run <script> 而非 python3 <script>。
  • 使用工厂模式进行依赖注入。

使用方式(资料中的示例)

应用结构示例:

import typer
from rich.console import Console

app = typer.Typer()
console = Console()

@app.command()
def process(
    input_file: Annotated[Path, typer.Argument(help="Input file")],
    verbose: Annotated[bool, typer.Option("--verbose", "-v")] = False,
) -> None:
    """Process input file."""
    ...

Rich 宽度处理示例:

from rich.console import Console
from rich.table import Table
from rich.measure import Measurement

def get_table_width(table: Table) -> int:
    temp = Console(width=9999)
    m = Measurement.get(temp, temp.options, table)
    return int(m.maximum)

测试示例:

from typer.testing import CliRunner

runner = CliRunner()

def test_app_runs() -> None:
    result = runner.invoke(app, ["--help"])
    assert result.exit_code == 0

异步并发示例(使用 semaphore 处理 I/O 密集型 CLI 任务):

import asyncio
import typer
from typing import Annotated

@app.command()
def fetch(urls: Annotated[list[str], typer.Argument()], max_concurrent: Annotated[int, typer.Option()] = 10) -> None:
    """Fetch multiple URLs concurrently."""
    results = asyncio.run(_fetch_all(urls, max_concurrent))
    for result in results:
        console.print(result)

async def _fetch_all(urls: list[str], limit: int) -> list[str]:
    sem = asyncio.Semaphore(limit)
    async with httpx.AsyncClient() as client:
        tasks = [_fetch_one(client, u, sem) for u in urls]
        return await asyncio.gather(*tasks)

PEP 723 Shebang 示例:

#!/usr/bin/env -S uv run --quiet --script
# /// script
# requires-python = ">=3.11"
# dependencies = ["typer>=0.21", "rich>=13.0"]  # human-facing example only
# ///

参考文档与相关技能

资料列出的参考文档覆盖 Typer 命令、参数、参数类型、高级模式、子命令与测试;Rich 的 console 与 markup、renderables、文本与语法、高级模式、进度与实时显示、日志与回溯;以及 Typer 与 Rich 的集成、非 TTY、表格、异常处理与测试模式。

相关技能方面:涉及 Textual TUI 组件、屏幕栈、CSS 样式、响应式属性、Pilot 测试或后台任务时,加载 python-engineering:textual;聚焦 Typer 命令、参数配置、子命令组合或 Typer 专属文档时,加载 python-engineering:typer;涉及非 TTY 场景下的 Rich 表格渲染、Typer/Rich 集成陷阱或 CLI 输出处理正确性审查时,加载 python-engineering:typer-and-rich。

资料还提供示例资产:assets/python-cli-demo.py(完整可运行示例)、assets/typer_examples/index.md(演示非 TTY 显示方案,如 Panel/Table 宽度、换行、裁剪)、assets/nested-typer-exceptions/(Typer 嵌套异常反模式与修复的可运行演示)。

适用场景与限制

该资料适用于用 Typer 构建命令、用 Annotated 语法定义参数与选项、为智能体或人类设计 CLI 输出、以及为 Typer 应用编写测试等任务。资料中要求使用时参考 standards-for-python-development 获取共享规则,并加载 python3-testing 获取测试模式。关于具体收费、价格、支持平台或实际效果,资料中暂未提供,无法确认。