Automagic shell tab completion for Python CLI applications

1.8.0 · active · verified Thu Apr 09

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.

Warnings

Install

Imports

Quickstart

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.

import argparse
import shtab
import os

def get_main_parser():
    parser = argparse.ArgumentParser(prog='mycli', description='A simple CLI tool')
    parser.add_argument('--auth-key', type=str, default=os.environ.get('MYCLI_AUTH_KEY', ''), help='Authentication key')
    parser.add_argument('--output', '-o', choices=['json', 'yaml', 'text'], default='text', help='Output format')
    parser.add_argument('command', choices=['status', 'run', 'config'], help='Command to execute')
    return parser

if __name__ == '__main__':
    parser = get_main_parser()
    
    # Integrate shtab for completion. This creates a hidden argument like --print-completion
    shtab.add_argument(parser, shells=['bash', 'zsh', 'tcsh'])
    
    args = parser.parse_args()

    # Example of how a user would generate and install completion:
    # mycli --print-completion bash > ~/.bashrc.d/mycli.bash-completion
    # source ~/.bashrc.d/mycli.bash-completion
    
    print(f"Running command: {args.command}")
    if args.auth_key:
        print("Auth key provided.")
    else:
        print("No auth key provided.")
    print(f"Output format: {args.output}")

view raw JSON →