Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

click

БесплатноБез исполняемых скриптовНе проверен

Click is the Python library for building command-line tools from decorated functions: it parses options and arguments, validates types, prompts for missing…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

Click — Python command-line interfaces from decorated functions

Overview

Click turns a Python function into a command: decorators declare the options and arguments, Click parses sys.argv, converts and validates each value, and generates --help. Commands nest into groups of any depth, values can fall back to environment variables or interactive prompts, and click.testing.CliRunner runs a command in-process for tests. Click is the engine underneath Typer and Flask's CLI. It is a Python library; for Node.js CLIs see the commander skill.

Everything below was run against Click 8.5.0 (current on PyPI in November 2026), which requires Python 3.10+.

Instructions

Install

Install into the project's virtual environment, never system Python.

python3 -m venv .venv
.venv/bin/pip install "click>=8.2"

One command

Options start with -, arguments are positional. The parameter name is derived from the longest flag (--dry-run becomes dry_run) unless you give a name as a plain string.

import click


@click.command()
@click.argument("database")
@click.option("--keep", type=click.IntRange(min=1, max=90), default=7, show_default=True,
              help="Number of backups to retain.")
@click.option("--dry-run", is_flag=True, help="Print the plan without writing.")
def backup(database, keep, dry_run):
    """Back up DATABASE and keep the newest backups."""
    click.echo(f"{database}: keeping {keep}, dry run={dry_run}")


if __name__ == "__main__":
    backup()

The docstring becomes the help text. Use click.echo rather than print (it handles encodings and pipes), and err=True for diagnostics so stdout stays machine-readable.

Groups, shared state, and the root options

A group is a command whose subcommands are registered with @group.command(). Options on the group run first; pass what subcommands need through ctx.obj.

@click.group(context_settings={"help_option_names": ["-h", "--help"]})
@click.version_option(package_name="backupctl")
@click.option("-v", "--verbose", count=True, help="Repeat for more detail (-vv).")
@click.pass_context
def main(ctx, verbose):
    """Manage nightly database backups."""
    ctx.ensure_object(dict)
    ctx.obj["verbose"] = verbose


@main.command()
@click.pass_context
def status(ctx):
    """Show the last backup."""
    if ctx.obj["verbose"]:
        click.echo("reading state file", err=True)
    click.echo("last backup: 2026-11-04 02:00")

version_option(package_name=...) reads the installed package's version from its metadata. count=True turns repeated -v into an integer. Do not read click.__version__: it is deprecated since 8.2 and removed in 9.1; use importlib.metadata.version("click").

Types and validation

Need Use
Closed set of strings click.Choice(["sql", "custom"], case_sensitive=False)
Bounded number click.IntRange(min=1, max=90), click.FloatRange(...)
File or directory path click.Path(exists=True, dir_okay=False, path_type=Path)
Open file (supports - for stdin/stdout) click.File("r")
Date click.DateTime(formats=["%Y-%m-%d"])

A violation prints Error: Invalid value for '--keep': ... with exit code 2 and no traceback. For your own checks raise click.UsageError("...") (exit 2) or click.ClickException("...") (exit 1) from inside the command.

Environment variables, prompts, secrets, repeats

@main.command()
@click.argument("database")
@click.option("--keep", type=click.IntRange(min=1, max=90), default=7, show_default=True,
              help="Number of backups to retain.")
@click.option("--token", envvar="BACKUPCTL_TOKEN", prompt=True, hide_input=True,
              help="API token; read from BACKUPCTL_TOKEN or prompted.")
@click.option("--tag", "tags", multiple=True, help="Label to attach; repeatable.")
@click.option("--format", "fmt", type=click.Choice(["sql", "custom"]), default="sql")
def run(database, keep, token, tags, fmt):
    """Run a backup of DATABASE."""
    click.echo(f"{database}: keep={keep} tags={list(tags)} format={fmt}")

Resolution order is the command line, then envvar, then default, then the prompt. With prompt=True the prompt only appears when no value was found, so a CI job that sets the variable never blocks. multiple=True gives a tuple (empty when the option is absent). Use click.confirm("Delete every backup?", abort=True) before destructive steps; answering no exits with code 1 and prints Aborted!.

Auto-read all options from a prefix with @click.group(context_settings={"auto_envvar_prefix": "BACKUPCTL"}) (variable names become BACKUPCTL_<COMMAND>_<OPTION> for subcommand options).

Package it as an installable command

Put the code in src/backupctl/cli.py, expose the group as main, and declare the script in pyproject.toml:

[project]
name = "backupctl"
version = "0.1.0"
requires-python = ">=3.10"
dependencies = ["click>=8.2"]

[project.script
Полный SKILL.md на GitHub

Установить click в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл click?

Click is the Python library for building command-line tools from decorated functions: it parses options and arguments, validates types, prompts for missing values, and writes the --help pages. Use when a user asks to "build a Python CLI", "add a subcommand", "add an option with an environment variable fallback", "prompt for a password", "test a click command with CliRunner", "package a CLI with pyproject.toml scripts", or "add shell completion". Covers Click 8.2 to 8.5.

Как установить скилл click?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл click запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить click с