building-clis

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Building CLIs

构建命令行界面(CLI)

Build professional command-line interfaces across Python, Go, and Rust using modern frameworks with robust argument parsing, configuration management, and shell integration.
使用具备强大参数解析、配置管理和Shell集成能力的现代框架,在Python、Go和Rust中构建专业的命令行界面。

When to Use This Skill

何时使用该技能

Use this skill when:
  • Building developer tooling or automation CLIs
  • Creating infrastructure management tools (deployment, monitoring)
  • Implementing API client command-line tools
  • Adding CLI capabilities to existing projects
  • Packaging utilities for distribution (PyPI, Homebrew, binary releases)
Common triggers: "create a CLI tool", "build a command-line interface", "add CLI arguments", "parse command-line options", "generate shell completions"
适用于以下场景:
  • 构建开发者工具或自动化CLI
  • 创建基础设施管理工具(部署、监控)
  • 实现API客户端命令行工具
  • 为现有项目添加CLI功能
  • 打包实用工具以便分发(PyPI、Homebrew、二进制发布)
常见触发场景:"创建CLI工具"、"构建命令行界面"、"添加CLI参数"、"解析命令行选项"、"生成Shell补全"

Framework Selection

框架选择

Quick Decision Guide

快速决策指南

Python Projects:
  • Typer (recommended): Modern type-safe CLIs with minimal boilerplate
  • Click: Mature, flexible CLIs for complex command hierarchies
Go Projects:
  • Cobra (recommended): Industry standard for enterprise tools (Kubernetes, Docker, GitHub CLI)
  • urfave/cli: Lightweight alternative for simple CLIs
Rust Projects:
  • clap v4 (recommended): Type-safe with derive API or builder API for runtime flexibility
For detailed framework comparison and selection criteria, see references/framework-selection.md.
Python项目:
  • Typer(推荐):现代类型安全的CLI,所需样板代码极少
  • Click:适用于复杂命令层级的成熟、灵活的CLI
Go项目:
  • Cobra(推荐):企业级工具的行业标准(Kubernetes、Docker、GitHub CLI均使用)
  • urfave/cli:适用于简单CLI的轻量替代方案
Rust项目:
  • clap v4(推荐):支持derive API或运行时灵活的Builder API的类型安全框架
如需详细的框架对比和选择标准,请查看references/framework-selection.md

Core Patterns

核心模式

Arguments vs. Options vs. Flags

参数、选项与标志

Positional Arguments:
  • Primary input, identified by position
  • Use for required inputs (max 2-3 arguments)
  • Example:
    convert input.jpg output.png
Options:
  • Named parameters with values
  • Use for configuration and optional inputs
  • Example:
    --output file.txt
    ,
    --config app.yaml
Flags:
  • Boolean options (presence = true)
  • Use for switches and toggles
  • Example:
    --verbose
    ,
    --dry-run
    ,
    --force
Decision Matrix:
Use CaseTypeExample
Primary required inputPositional Argument
git commit -m "message"
Optional configurationOption
--config app.yaml
Boolean settingFlag
--verbose
,
--force
Multiple valuesVariadic Argument
files...
See references/argument-patterns.md for comprehensive parsing patterns.
位置参数:
  • 主要输入,通过位置识别
  • 用于必填输入(最多2-3个参数)
  • 示例:
    convert input.jpg output.png
选项:
  • 带值的命名参数
  • 用于配置和可选输入
  • 示例:
    --output file.txt
    ,
    --config app.yaml
标志:
  • 布尔型选项(存在即表示true)
  • 用于开关和切换
  • 示例:
    --verbose
    ,
    --dry-run
    ,
    --force
决策矩阵:
使用场景类型示例
主要必填输入位置参数
git commit -m "message"
可选配置选项
--config app.yaml
布尔设置标志
--verbose
,
--force
多值输入可变参数
files...
如需全面的解析模式,请查看references/argument-patterns.md

Subcommand Organization

子命令组织

Flat Structure (1 Level):
app command1 [args]
app command2 [args]
Use for: Small CLIs with 5-10 operations
Grouped Structure (2 Levels):
app group subcommand [args]
Use for: Medium CLIs with logical groupings (10-30 commands) Example:
kubectl get pods
,
kubectl create deployment
Nested Structure (3+ Levels):
app group subgroup command [args]
Use for: Large CLIs with deep hierarchies (30+ commands) Example:
gcloud compute instances create
See references/subcommand-design.md for structuring strategies.
扁平结构(1级):
app command1 [args]
app command2 [args]
适用场景:包含5-10个操作的小型CLI
分组结构(2级):
app group subcommand [args]
适用场景:包含逻辑分组的中型CLI(10-30个命令) 示例:
kubectl get pods
,
kubectl create deployment
嵌套结构(3级及以上):
app group subgroup command [args]
适用场景:包含深层层级的大型CLI(30个以上命令) 示例:
gcloud compute instances create
如需结构化策略,请查看references/subcommand-design.md

Configuration Management

配置管理

Standard Precedence (Highest to Lowest):
  1. CLI Arguments/Flags (explicit user input)
  2. Environment Variables (session overrides)
  3. Config File - Local (
    ./config.yaml
    )
  4. Config File - User (
    ~/.config/app/config.yaml
    )
  5. Config File - System (
    /etc/app/config.yaml
    )
  6. Built-in Defaults (hardcoded)
Best Practices:
  • Document precedence in
    --help
  • Validate config files before execution
  • Provide
    --print-config
    to show effective configuration
  • Use XDG Base Directory (
    ~/.config/app/
    ) for config files
See references/configuration-management.md for implementation patterns across languages.
标准优先级(从高到低):
  1. CLI参数/标志(用户显式输入)
  2. 环境变量(会话覆盖)
  3. 本地配置文件(
    ./config.yaml
  4. 用户配置文件(
    ~/.config/app/config.yaml
  5. 系统配置文件(
    /etc/app/config.yaml
  6. 内置默认值(硬编码)
最佳实践:
  • --help
    中说明优先级
  • 执行前验证配置文件
  • 提供
    --print-config
    以显示生效的配置
  • 使用XDG基础目录(
    ~/.config/app/
    )存储配置文件
如需跨语言的实现模式,请查看references/configuration-management.md

Output Formatting

输出格式

Format Selection:
Use CaseFormatWhen
Human consumptionColored text, tablesDefault interactive mode
Machine consumptionJSON, YAML
--output json
, piping
Logging/debuggingPlain text
--verbose
, stderr
Progress trackingProgress bars, spinnersLong operations
Best Practices:
  • Default to human-readable output
  • Provide
    --output
    flag (json, yaml, table)
  • Use stderr for logs, stdout for data
  • Auto-detect TTY (disable colors if not interactive)
  • Use exit codes: 0 = success, 1 = error, 2 = usage error
See references/output-formatting.md for formatting strategies.
格式选择:
使用场景格式适用时机
人类阅读彩色文本、表格默认交互模式
机器解析JSON、YAML
--output json
、管道输出
日志/调试纯文本
--verbose
、标准错误输出(stderr)
进度跟踪进度条、加载动画耗时操作
最佳实践:
  • 默认使用人类可读的输出
  • 提供
    --output
    标志(支持json、yaml、table)
  • 日志输出到stderr,数据输出到stdout
  • 自动检测TTY(非交互模式下禁用颜色)
  • 使用退出码:0=成功,1=错误,2=用法错误
如需格式化策略,请查看references/output-formatting.md

Language-Specific Quick Starts

各语言快速入门

Python with Typer

使用Typer构建Python CLI

Installation:
bash
pip install "typer[all]"  # Includes rich for colored output
Basic Example:
python
import typer
from typing import Annotated

app = typer.Typer()

@app.command()
def greet(
    name: Annotated[str, typer.Argument(help="Name to greet")],
    formal: Annotated[bool, typer.Option(help="Use formal greeting")] = False
):
    """Greet someone with a message."""
    greeting = "Good day" if formal else "Hello"
    typer.echo(f"{greeting}, {name}!")

if __name__ == "__main__":
    app()
Key Features:
  • Type hints for automatic validation
  • Minimal boilerplate with decorators
  • Auto-generated help text
  • Rich integration for colored output
See examples/python/ for complete working examples including subcommands, config management, and interactive features.
安装:
bash
pip install "typer[all]"  # Includes rich for colored output
基础示例:
python
import typer
from typing import Annotated

app = typer.Typer()

@app.command()
def greet(
    name: Annotated[str, typer.Argument(help="Name to greet")],
    formal: Annotated[bool, typer.Option(help="Use formal greeting")] = False
):
    """Greet someone with a message."""
    greeting = "Good day" if formal else "Hello"
    typer.echo(f"{greeting}, {name}!")

if __name__ == "__main__":
    app()
核心特性:
  • 类型提示自动验证
  • 装饰器减少样板代码
  • 自动生成帮助文本
  • 集成rich实现彩色输出
如需完整的工作示例(包括子命令、配置管理和交互功能),请查看examples/python/

Go with Cobra

使用Cobra构建Go CLI

Installation:
bash
go get -u github.com/spf13/cobra@latest
Basic Example:
go
var rootCmd = &cobra.Command{
    Use:   "greet [name]",
    Args:  cobra.ExactArgs(1),
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Printf("Hello, %s!\n", args[0])
    },
}

rootCmd.Flags().Bool("formal", false, "Use formal greeting")
rootCmd.Execute()
Key Features:
  • POSIX-compliant flags
  • Viper integration for configuration
  • Subcommand architecture
  • Shell completion generation
See examples/go/ for complete working examples including Viper config and multi-level subcommands.
安装:
bash
go get -u github.com/spf13/cobra@latest
基础示例:
go
var rootCmd = &cobra.Command{
    Use:   "greet [name]",
    Args:  cobra.ExactArgs(1),
    Run: func(cmd *cobra.Command, args []string) {
        fmt.Printf("Hello, %s!\n", args[0])
    },
}

rootCmd.Flags().Bool("formal", false, "Use formal greeting")
rootCmd.Execute()
核心特性:
  • 符合POSIX标准的标志
  • 集成Viper进行配置管理
  • 子命令架构
  • 生成Shell补全
如需完整的工作示例(包括Viper配置和多级子命令),请查看examples/go/

Rust with clap

使用clap构建Rust CLI

Installation (Cargo.toml):
toml
[dependencies]
clap = { version = "4.5", features = ["derive"] }
Basic Example (Derive API):
rust
use clap::Parser;

#[derive(Parser)]
#[command(about = "Greet someone")]
struct Cli {
    /// Name to greet
    name: String,

    /// Use formal greeting
    #[arg(long)]
    formal: bool,
}

fn main() {
    let cli = Cli::parse();
    let greeting = if cli.formal { "Good day" } else { "Hello" };
    println!("{}, {}!", greeting, cli.name);
}
Key Features:
  • Compile-time type safety
  • Derive API (declarative) or Builder API (programmatic)
  • Comprehensive validation
  • Performance optimized
See examples/rust/ for complete working examples including subcommands and builder API patterns.
安装(Cargo.toml):
toml
[dependencies]
clap = { version = "4.5", features = ["derive"] }
基础示例(Derive API):
rust
use clap::Parser;

#[derive(Parser)]
#[command(about = "Greet someone")]
struct Cli {
    /// Name to greet
    name: String,

    /// Use formal greeting
    #[arg(long)]
    formal: bool,
}

fn main() {
    let cli = Cli::parse();
    let greeting = if cli.formal { "Good day" } else { "Hello" };
    println!("{}, {}!", greeting, cli.name);
}
核心特性:
  • 编译时类型安全
  • 支持Derive API(声明式)或Builder API(编程式)
  • 全面的验证
  • 性能优化
如需完整的工作示例(包括子命令和Builder API模式),请查看examples/rust/

Interactive Features

交互功能

Progress Indicators

进度指示器

Python (rich):
python
from rich.progress import track
for _ in track(range(100), description="Processing..."):
    time.sleep(0.01)
Go (progressbar):
go
import "github.com/schollz/progressbar/v3"
bar := progressbar.Default(100)
for i := 0; i < 100; i++ {
    bar.Add(1)
}
Rust (indicatif):
rust
use indicatif::ProgressBar;
let bar = ProgressBar::new(100);
for _ in 0..100 {
    bar.inc(1);
}
Python(rich):
python
from rich.progress import track
for _ in track(range(100), description="Processing..."):
    time.sleep(0.01)
Go(progressbar):
go
import "github.com/schollz/progressbar/v3"
bar := progressbar.Default(100)
for i := 0; i < 100; i++ {
    bar.Add(1)
}
Rust(indicatif):
rust
use indicatif::ProgressBar;
let bar = ProgressBar::new(100);
for _ in 0..100 {
    bar.inc(1);
}

Prompts and Confirmations

提示与确认

Python:
python
confirm = typer.confirm("Are you sure?")
if not confirm:
    raise typer.Abort()
Go:
go
reader := bufio.NewReader(os.Stdin)
fmt.Print("Are you sure? (y/n): ")
response, _ := reader.ReadString('\n')
Rust:
rust
use dialoguer::Confirm;
if Confirm::new().with_prompt("Are you sure?").interact()? {
    // Proceed
}
Python:
python
confirm = typer.confirm("Are you sure?")
if not confirm:
    raise typer.Abort()
Go:
go
reader := bufio.NewReader(os.Stdin)
fmt.Print("Are you sure? (y/n): ")
response, _ := reader.ReadString('\n')
Rust:
rust
use dialoguer::Confirm;
if Confirm::new().with_prompt("Are you sure?").interact()? {
    // Proceed
}

Shell Completion

Shell补全

Generating Completions

生成补全

Python (Typer):
bash
_MYAPP_COMPLETE=bash_source myapp > ~/.myapp-complete.bash
_MYAPP_COMPLETE=zsh_source myapp > ~/.myapp-complete.zsh
Go (Cobra):
go
rootCmd.AddCommand(&cobra.Command{
    Use:   "completion [bash|zsh|fish|powershell]",
    Args:  cobra.ExactArgs(1),
    Run: func(cmd *cobra.Command, args []string) {
        switch args[0] {
        case "bash":
            rootCmd.GenBashCompletion(os.Stdout)
        case "zsh":
            rootCmd.GenZshCompletion(os.Stdout)
        }
    },
})
Rust (clap):
rust
use clap_complete::{generate, shells::Bash};
generate(Bash, &mut Cli::command(), "myapp", &mut io::stdout())
See references/shell-completion.md for installation instructions.
Python(Typer):
bash
_MYAPP_COMPLETE=bash_source myapp > ~/.myapp-complete.bash
_MYAPP_COMPLETE=zsh_source myapp > ~/.myapp-complete.zsh
Go(Cobra):
go
rootCmd.AddCommand(&cobra.Command{
    Use:   "completion [bash|zsh|fish|powershell]",
    Args:  cobra.ExactArgs(1),
    Run: func(cmd *cobra.Command, args []string) {
        switch args[0] {
        case "bash":
            rootCmd.GenBashCompletion(os.Stdout)
        case "zsh":
            rootCmd.GenZshCompletion(os.Stdout)
        }
    },
})
Rust(clap):
rust
use clap_complete::{generate, shells::Bash};
generate(Bash, &mut Cli::command(), "myapp", &mut io::stdout())
如需安装说明,请查看references/shell-completion.md

Distribution and Packaging

分发与打包

Python (PyPI)

Python(PyPI)

pyproject.toml:
toml
[project]
name = "myapp"
version = "1.0.0"
scripts = { myapp = "myapp.cli:app" }
Publish:
bash
pip install build twine
python -m build
twine upload dist/*
pyproject.toml:
toml
[project]
name = "myapp"
version = "1.0.0"
scripts = { myapp = "myapp.cli:app" }
发布:
bash
pip install build twine
python -m build
twine upload dist/*

Go (Homebrew)

Go(Homebrew)

Formula:
ruby
class Myapp < Formula
  desc "My CLI application"
  url "https://github.com/user/myapp/archive/v1.0.0.tar.gz"

  def install
    system "go", "build", "-o", bin/"myapp"
  end
end
Formula:
ruby
class Myapp < Formula
  desc "My CLI application"
  url "https://github.com/user/myapp/archive/v1.0.0.tar.gz"

  def install
    system "go", "build", "-o", bin/"myapp"
  end
end

Rust (Cargo)

Rust(Cargo)

Publish:
bash
cargo login
cargo publish
Installation:
bash
cargo install myapp
See references/distribution.md for comprehensive packaging strategies including binary releases.
发布:
bash
cargo login
cargo publish
安装:
bash
cargo install myapp
如需全面的打包策略(包括二进制发布),请查看references/distribution.md

Best Practices

最佳实践

Universal CLI Conventions

通用CLI约定

Always Provide:
  • --help
    and
    -h
    for usage information
  • --version
    and
    -V
    for version display
  • Clear error messages with actionable suggestions
Argument Handling:
  • Use
    --
    separator for options vs. positional args
  • Support both short (
    -v
    ) and long (
    --verbose
    ) forms
  • Validate and sanitize all user inputs
Error Handling:
  • Exit code 0 for success
  • Exit code 1 for general errors
  • Exit code 2 for usage errors
  • Write errors to stderr, data to stdout
Interactivity:
  • Detect TTY (interactive vs. piped input)
  • Provide
    --yes
    /
    --force
    to skip prompts for automation
  • Show progress for operations longer than 2 seconds
始终提供:
  • --help
    -h
    查看使用信息
  • --version
    -V
    查看版本信息
  • 清晰的错误消息及可操作建议
参数处理:
  • 使用
    --
    分隔选项和位置参数
  • 同时支持短选项(
    -v
    )和长选项(
    --verbose
  • 验证并清理所有用户输入
错误处理:
  • 退出码0表示成功
  • 退出码1表示一般错误
  • 退出码2表示用法错误
  • 错误输出到stderr,数据输出到stdout
交互性:
  • 检测TTY(交互模式 vs 管道输入)
  • 提供
    --yes
    /
    --force
    跳过提示以支持自动化
  • 对耗时超过2秒的操作显示进度

Configuration Best Practices

配置最佳实践

File Formats:
  • Use YAML, TOML, or JSON consistently
  • Separate files per environment (dev, staging, prod)
  • Validate configuration in CI/CD with
    --check-config
Secret Management:
  • Never commit secrets to config files
  • Use environment variables or secret managers
  • Document required environment variables
Precedence:
  • CLI args > env vars > config file > defaults
  • Document precedence in help text
  • Provide
    --print-config
    to show effective configuration
文件格式:
  • 统一使用YAML、TOML或JSON
  • 为不同环境(开发、 staging、生产)使用单独的配置文件
  • 在CI/CD中使用
    --check-config
    验证配置
密钥管理:
  • 切勿将密钥提交到配置文件
  • 使用环境变量或密钥管理器
  • 记录所需的环境变量
优先级:
  • CLI参数 > 环境变量 > 配置文件 > 默认值
  • 在帮助文本中说明优先级
  • 提供
    --print-config
    以显示生效的配置

Integration with Other Skills

与其他技能的集成

testing-strategies:
  • CLI testing with mocks and fixtures
  • Integration tests for end-to-end workflows
  • See examples/python/test_cli.py
building-ci-pipelines:
  • Binary builds for multiple platforms
  • Automated releases via GitHub Actions
  • See references/distribution.md
api-patterns:
  • Building API client CLIs
  • Authentication and token management
  • Formatting API responses
secret-management:
  • Secure credential storage
  • Environment variable integration
  • Vault/secrets manager integration
testing-strategies:
  • 使用模拟和测试夹具进行CLI测试
  • 端到端工作流的集成测试
  • 查看examples/python/test_cli.py
building-ci-pipelines:
  • 多平台二进制构建
  • 通过GitHub Actions自动发布
  • 查看references/distribution.md
api-patterns:
  • 构建API客户端CLI
  • 认证和令牌管理
  • API响应格式化
secret-management:
  • 安全的凭证存储
  • 环境变量集成
  • 与Vault/密钥管理器集成

Reference Files

参考文件

Decision Frameworks:
  • framework-selection.md - Which framework to choose
  • argument-patterns.md - Arguments vs. options vs. flags
  • subcommand-design.md - Structuring command hierarchies
Implementation Guides:
  • configuration-management.md - Config files and precedence
  • output-formatting.md - Human vs. machine-readable output
  • shell-completion.md - Generating completions
  • distribution.md - Packaging and releasing CLIs
Code Examples:
  • examples/python/ - Typer examples (basic, subcommands, config, interactive)
  • examples/go/ - Cobra examples (basic, subcommands, Viper integration)
  • examples/rust/ - clap examples (derive, builder, subcommands)
决策框架:
  • framework-selection.md - 如何选择框架
  • argument-patterns.md - 参数、选项与标志对比
  • subcommand-design.md - 命令层级结构化策略
实现指南:
  • configuration-management.md - 配置文件与优先级
  • output-formatting.md - 人类可读 vs 机器可读输出
  • shell-completion.md - 生成补全
  • distribution.md - CLI打包与发布
代码示例:
  • examples/python/ - Typer示例(基础、子命令、配置、交互)
  • examples/go/ - Cobra示例(基础、子命令、Viper集成)
  • examples/rust/ - clap示例(Derive、Builder、子命令)

Quick Reference

快速参考

Framework Recommendations:
  • Python: Typer (modern) or Click (mature)
  • Go: Cobra (enterprise) or urfave/cli (simple)
  • Rust: clap v4 (derive or builder)
Common Patterns:
  • Arguments: Primary inputs (max 2-3)
  • Options: Named parameters with values
  • Flags: Boolean switches
  • Subcommands: Group related operations
  • Config: CLI args > env vars > files > defaults
Output Standards:
  • Default: Human-readable (colored, tables)
  • Machine: JSON/YAML via
    --output
    flag
  • Errors: stderr, data: stdout
  • Exit: 0 = success, 1 = error, 2 = usage
Distribution:
  • Python: PyPI (
    pip install
    )
  • Go: Homebrew, binary releases
  • Rust: Cargo (
    cargo install
    ), binary releases
框架推荐:
  • Python:Typer(现代)或Click(成熟)
  • Go:Cobra(企业级)或urfave/cli(简单)
  • Rust:clap v4(Derive或Builder)
通用模式:
  • 参数:主要输入(最多2-3个)
  • 选项:带值的命名参数
  • 标志:布尔开关
  • 子命令:分组相关操作
  • 配置:CLI参数 > 环境变量 > 文件 > 默认值
输出标准:
  • 默认:人类可读(彩色、表格)
  • 机器解析:通过
    --output
    标志输出JSON/YAML
  • 错误:输出到stderr,数据:输出到stdout
  • 退出码:0=成功,1=错误,2=用法错误
分发方式:
  • Python:PyPI(
    pip install
  • Go:Homebrew、二进制发布
  • Rust:Cargo(
    cargo install
    )、二进制发布