CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-argcomplete

Bash tab completion for argparse

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

Overview
Eval results
Files

completion-engine.mddocs/

Core Completion Engine

The core completion system provides the primary interface for enabling tab completion in Python scripts using argparse. The completion engine intercepts argparse operations during shell completion and generates appropriate completion candidates.

Capabilities

Main Completion Interface

The primary interface for adding completion to argparse-based scripts. This is a pre-instantiated CompletionFinder instance.

autocomplete: CompletionFinder  # Pre-instantiated completion finder

# Equivalent to: CompletionFinder().__call__(parser, **kwargs)

The autocomplete instance accepts the same parameters as CompletionFinder.call():

  • argument_parser: The argparse ArgumentParser to enable completion on
  • always_complete_options: Controls completion of option strings (True, False, "long", "short")
  • exit_method: Method to exit after completion (default: os._exit)
  • output_stream: Stream for completion output (default: file descriptor 8)
  • exclude: List of option strings to exclude from completion
  • validator: Function to filter completions (receives completion and prefix)
  • print_suppressed: Whether to complete suppressed options
  • append_space: Whether to append space to unique matches
  • default_completer: Completer used when no specific completer is set

Usage:

#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK

import argparse
import argcomplete

parser = argparse.ArgumentParser()
parser.add_argument('--verbose', action='store_true')
parser.add_argument('--output', type=argparse.FileType('w'))

# Enable completion
argcomplete.autocomplete(parser)

args = parser.parse_args()

CompletionFinder Class

Core class for finding and generating completions. Inherit from this class to customize completion behavior.

class CompletionFinder:
    def __init__(
        self,
        argument_parser=None,
        always_complete_options=True,
        exclude=None,
        validator=None,
        print_suppressed=False,
        default_completer=FilesCompleter(),
        append_space=None
    )

Main Completion Method:

def __call__(
    self,
    argument_parser: argparse.ArgumentParser,
    always_complete_options: Union[bool, str] = True,
    exit_method: Callable = os._exit,
    output_stream: Optional[TextIO] = None,
    exclude: Optional[Sequence[str]] = None,
    validator: Optional[Callable] = None,
    print_suppressed: bool = False,
    append_space: Optional[bool] = None,
    default_completer: BaseCompleter = FilesCompleter()
) -> None

Completion Collection Methods:

def collect_completions(
    self, 
    active_parsers: List[argparse.ArgumentParser], 
    parsed_args: argparse.Namespace, 
    cword_prefix: str
) -> List[str]
def filter_completions(self, completions: List[str]) -> List[str]
def quote_completions(
    self, 
    completions: List[str], 
    cword_prequote: str, 
    last_wordbreak_pos: Optional[int]
) -> List[str]

Readline Integration:

def rl_complete(self, text: str, state: int) -> Optional[str]
def get_display_completions(self) -> Dict[str, str]

Usage:

import argcomplete

# Custom completion finder
completer = argcomplete.CompletionFinder(
    always_complete_options="long",
    exclude=["--debug"],
    validator=lambda completion, prefix: not completion.startswith("_")
)

# Use with parser
completer(parser)

# Or for readline integration
import readline
readline.set_completer(completer.rl_complete)
readline.parse_and_bind("tab: complete")

ExclusiveCompletionFinder

Variant of CompletionFinder that provides exclusive completion behavior, preventing completion of conflicting options.

class ExclusiveCompletionFinder(CompletionFinder):
    """
    CompletionFinder that only completes options that haven't been used yet,
    except for append actions which can be used multiple times.
    """

Usage:

import argcomplete

finder = argcomplete.ExclusiveCompletionFinder()
finder(parser)

Advanced Usage

Custom Validator

def custom_validator(completion, prefix):
    """Only allow completions that don't start with underscore"""
    return not completion.startswith('_')

argcomplete.autocomplete(parser, validator=custom_validator)

Output Stream Redirection

import io

output_buffer = io.StringIO()
argcomplete.autocomplete(parser, output_stream=output_buffer)

Exception Handling

The completion engine uses ArgcompleteException for completion-related errors:

from argcomplete import ArgcompleteException

try:
    argcomplete.autocomplete(parser)
except ArgcompleteException as e:
    print(f"Completion error: {e}")

Install with Tessl CLI

npx tessl i tessl/pypi-argcomplete

docs

completers.md

completion-engine.md

index.md

scripts.md

shell-integration.md

utilities.md

tile.json