building-python-clis について
Python コマンドラインツールの開発とテストを支援するスキルです。フレームワークの選択、エントリーポイント、一般的な実装パターン、シェル補完、Click の CliRunner によるテストを扱います。
主な機能
- 01Click、Typer、argparse の選択ガイド
- 02pyproject.toml のエントリーポイント設定
- 03ファイル入出力のパターン
- 04プログレスバーの使用
- 05CliRunner によるテストとシェル補完
活用シーン
- 01Python CLI フレームワークの選択
- 02パッケージへの CLI エントリーポイント追加
- 03コマンドと出力のテスト
- 04シェル補完スクリプトの生成
インストール
コマンドをコピーしてターミナルで実行します。
$
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
シェル補完
# 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 対応