Python の Click でコマンドライン引数を処理する
Click は argparse のようにコマンドライン引数を処理して、CLI ツールを作ることが出来ます。 今回は Click の簡単な使い方をメモしておきます。
検証環境¶
| 対象 | バージョン | 
|---|---|
| macOS | 14.5 | 
| Python | 3.11.9 | 
インストール¶
uv pip install click
公式サイトのチュートリアル¶
サンプルコード¶
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |  | 
実行結果¶
$ python3 sample.py
Your name: Alice
Hello, Alice!
$ python3 sample.py --count 3
Your name: Bob
Hello, Bob!
Hello, Bob!
Hello, Bob!
フォントに色を付ける¶
フォントや背景に色を付けることが出来ます。
サンプルコード¶
| 1 2 3 4 5 |  | 
実行結果¶

ヘルプに docstring を表示する¶
docstring の内容をヘルプに表示することが出来ます。
サンプルコード¶
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |  | 
実行結果¶
$ python3 help.py --help
Usage: help.py [OPTIONS] NAME
  This script prints hello NAME COUNT times.
Options:
  --count INTEGER  number of greetings
  --help           Show this message and exit.
サブコマンドを実装する¶
サブコマンドのことを click では Nesting Commands と呼ぶようです。
サンプルコード¶
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |  | 
実行結果¶
$ python3 subcommand.py --help
Usage: subcommand.py [OPTIONS] COMMAND [ARGS]...
Options:
  --help  Show this message and exit.
Commands:
  dropdb
  initdb
$ python3 subcommand.py dropdb
Dropped the database
$ python3 subcommand.py initdb
Initialized the database