shtab is a Python library that automatically generates shell tab completion scripts for command-line interface (CLI) applications. It processes an `argparse.ArgumentParser` object to produce completion scripts for `bash`, `zsh`, and `tcsh`. It aims for speed and correctness, avoiding the side-effects and performance issues of alternatives like `argcomplete` and `pyzshcomplete`. As of version 1.8.0, it is actively maintained by Iterative AI, with its development often driven by the needs of projects like DVC, but designed for general-purpose use.
pip install shtabVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to integrate `shtab` into an `argparse`-based CLI application. By calling `shtab.add_argument(parser)`, a hidden argument (e.g., `--print-completion`) is added to your parser, allowing users to generate completion scripts for their shell. Users would then run `python your_script.py --print-completion bash` to get the script and install it according to their shell's instructions (e.g., sourcing it in their `.bashrc`). The example includes common argparse features like choices and environment variable defaults.
Refer to `shtab` documentation for OS-specific installation steps for bash-completion or zsh completion. Ensure your shell config (`.bashrc`, `.zshrc`) properly sources completion files and that the generated script is in the correct location. Verify `shtab` and your application are in `PATH` and `PYTHONPATH` if necessary.
When using `shtab` from the CLI, add the `--error-unimportable` flag to get explicit error messages if the parser cannot be imported. Always ensure `argparse.ArgumentParser(prog="YOUR_CLI_NAME")` matches the name users will type, or use `shtab --prog=YOUR_CLI_NAME ...` to override it.