How to Add Auto-Completion to Click CLI Apps
If you’ve ever typed a long CLI command and immediately regretted your life choices, this article is for you. Typing out full command names, remembering options, and scrolling through help menus is so last century.
Wouldn’t it be great if your CLI app could just complete commands for you? Like magic? Well, good news: Click supports auto-completion!
In this guide, weโll:
- Enable auto-completion in Click-powered CLI apps.
- Set it up for Bash, Zsh, and Fish (sorry Windows users, life is hard).
- Make our CLI apps feel 10x smarter.
๐ฏ Why Auto-Completion?
โ
Saves you from typing long commands (because who has time for that?)
โ
Reduces typos (no more --frce
instead of --force
)
โ
Makes your CLI look polished and professional
Click has built-in auto-completion support, but it needs a little setup. Letโs do it.
๐ Step 1: Install Click Shell Completion
First, make sure you have Click 8.0+:
|
|
Now, letโs create a basic CLI app in cli.py
:
|
|
Run python cli.py --help
, and youโll see a basic CLI app with two commands.
Now, letโs add auto-completion.
๐ง Step 2: Enable Auto-Completion
Click supports shell completion, but we need to set it up manually.
Generate Completion Scripts
To enable completion, Click provides a built-in command:
|
|
This will output a shell completion script. You need to save this script and source it in your shell.
For Bash Users ๐ง
Save the script to your bash completion directory:
|
|
Or add it to .bashrc
:
|
|
For Zsh Users ๐ฆ
For Zsh, save the script to your completion functions:
|
|
For Fish Users ๐
Fish shell users can do:
|
|
Restart your shell, and auto-completion should work! ๐
๐ฎ Step 3: Test It!
Try typing:
|
|
You should see:
|
|
Now try:
|
|
It should auto-complete the command! You’re now a CLI wizard. ๐งโโ๏ธ
๐ Step 4: Making It Even Smarter
Want better auto-completion? Click lets you suggest values dynamically.
Letโs create a command with auto-completing options:
|
|
Now, when you type:
|
|
It will only suggest “red”, “green”, or “blue”! Smart, right?
๐ Wrapping Up
Today, you learned how to supercharge your Click CLI apps with:
โ
Auto-completion for commands and options
โ
Bash, Zsh, and Fish integration
โ
Dynamic suggestions for even better UX
Your CLI is now faster, smarter, and less frustrating to use. Congrats! ๐