Argcomplete
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
- gotcha The `# PYTHON_ARGCOMPLETE_OK` marker must be present within the first 1024 bytes of the script file for global completion to detect it. Incorrect placement can lead to completion not working.
- gotcha Heavy computations or side effects executed before `argcomplete.autocomplete(parser)` in your script will run every time tab completion is attempted. This can make completion sluggish and unresponsive, negatively impacting user experience.
- breaking Argcomplete requires Bash 4.2+ for global completion. Older Bash versions (e.g., Bash 3.2 on macOS by default) do not support the `complete -D` functionality needed, leading to global completion failures.
- breaking Specific argcomplete versions were required to maintain compatibility with changes in Python's `argparse` module, particularly with Python 3.11.9+, 3.12.3+, 3.12.8+, and 3.13.1+. Failing to update could result in completion errors or broken argument parsing.
- gotcha If your script tries to read from `stdin` during completion, it can cause the shell to lock up, as `argcomplete` typically redirects `stdin` during completion generation. This was explicitly addressed in v3.4.0.
- gotcha After debugging completion issues or if an older completion function was registered, the shell might retain a broken completion. This can manifest as `_minimal` being used or no completion at all.
Install
-
pip install argcomplete -
activate-global-python-argcomplete -
eval "$(register-python-argcomplete my-script.py)"
Imports
- argcomplete
import argcomplete
- autocomplete
from argcomplete import autocomplete
- ChoicesCompleter
from argcomplete.completers import ChoicesCompleter
- CompletionFinder
from argcomplete.completion_finder import CompletionFinder
Quickstart
#!/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()