Argcomplete

3.6.3 · active · verified Sun Mar 29

Argcomplete provides robust and extensible tab completion for command-line interfaces built with Python's `argparse` library. It enhances user experience by offering dynamic suggestions for arguments, options, and their values in shells like Bash and Zsh. The library is actively maintained with frequent releases, often including compatibility fixes for newer Python versions and shell environments.

Warnings

Install

Imports

Quickstart

Create a Python script (e.g., `my_cli.py`) with the `#!` shebang and the `# PYTHON_ARGCOMPLETE_OK` marker. Initialize your `ArgumentParser`, add arguments, and then call `argcomplete.autocomplete(parser)` before `parser.parse_args()`. To activate completion for this script in your shell, run `eval "$(register-python-argcomplete my_cli.py)"`. For global activation across all argcomplete-enabled scripts, run `activate-global-python-argcomplete` once.

#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
import argparse
import argcomplete

def main():
    parser = argparse.ArgumentParser(description='A simple CLI tool with completion.')
    parser.add_argument('--name', help='Your name').completer = argcomplete.completers.ChoicesCompleter(['Alice', 'Bob', 'Charlie'])
    parser.add_argument('--action', choices=['start', 'stop', 'restart'], help='Action to perform')

    # Enable argcomplete on the parser
    argcomplete.autocomplete(parser)

    args = parser.parse_args()

    if args.name:
        print(f"Hello, {args.name}!")
    if args.action:
        print(f"Performing action: {args.action}")

if __name__ == '__main__':
    main()

view raw JSON →