关于 building-python-clis
用于构建和测试 Python 命令行工具的开发 Skill,涵盖框架选择、入口配置、常见模式、Shell 补全及 Click CliRunner 测试。
主要功能
- 01Click、Typer 与 argparse 指引
- 02配置 pyproject.toml 入口
- 03文件输入与输出模式
- 04进度条用法
- 05CliRunner 测试与 Shell 补全
适用场景
- 01选择 Python 命令行框架
- 02为包添加命令行入口
- 03测试命令及其输出
- 04生成 Shell 补全脚本
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ wdm0006/ python-skills --skill building-python-clis安装后在 Claude Code 中输入/building-python-clis确认已加载。
附带文件CLICK_PATTERNS.mdTYPER_GUIDE.md
详细介绍
Python CLI 开发
框架选择
Click(推荐):成熟、功能丰富 Typer:现代化,专注于类型提示 argparse:零依赖,标准库
Click 快速入门
import click
@click.group()
@click.version_option(version='1.0.0')
def cli():
"""My CLI tool."""
pass
@cli.command()
@click.argument('input_file', type=click.Path(exists=True))
@click.option('--output', '-o', default='-', help='Output file')
@click.option('--verbose', '-v', is_flag=True)
def process(input_file, output, verbose):
"""Process an input file."""
if verbose:
click.echo(f"Processing {input_file}")
# ...
if __name__ == '__main__':
cli()
入口点(pyproject.toml)
[project.scripts]
mycli = "my_package.cli:cli"
[project.optional-dependencies]
cli = ["click>=8.0"]
常见模式
# File I/O with stdin/stdout support
@click.argument('input', type=click.File('r'), default='-')
@click.argument('output', type=click.File('w'), default='-')
# Progress bar
with click.progressbar(items, label='Processing') as bar:
for item in bar:
process(item)
# Colored output
click.secho("Success!", fg='green', bold=True)
click.secho("Error!", fg='red', err=True)
# Error handling
if not valid:
raise click.BadParameter(f'Invalid value: {value}')
使用 CliRunner 测试
from click.testing import CliRunner
from mypackage.cli import cli
def test_process():
runner = CliRunner()
result = runner.invoke(cli, ['process', 'input.txt'])
assert result.exit_code == 0
assert 'expected output' in result.output
def test_stdin():
runner = CliRunner()
result = runner.invoke(cli, ['process', '-'], input='test data\n')
assert result.exit_code == 0
Shell 补全
# Generate completion scripts
_MYCLI_COMPLETE=bash_source mycli > ~/.mycli-complete.bash
_MYCLI_COMPLETE=zsh_source mycli > ~/.mycli-complete.zsh
如需了解详细模式,请参阅:
- CLICK_PATTERNS.md - Click 高级用法
- TYPER_GUIDE.md - Typer 替代方案
CLI 检查清单
Setup:
- [ ] Entry point in pyproject.toml
- [ ] --help works for all commands
- [ ] --version displays version
UX:
- [ ] Errors go to stderr with non-zero exit
- [ ] Helpful error messages
- [ ] stdin/stdout support where appropriate
Testing:
- [ ] Tests for all commands
- [ ] Test error cases
- [ ] Test stdin processing
了解更多
此技能基于 Will McGinnis 编写的 高质量 Python 库开发指南。以下文章介绍了相关内容:
评论
支持 Markdown