Bash tab completion for argparse
—
Quality
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Support functions for debugging, output control, and command line parsing during completion operations. These utilities help with development, troubleshooting, and advanced completion scenarios.
Functions for controlling output during completion and debugging completion issues.
def debug(*args) -> None:
"""
Print debug information when _ARC_DEBUG environment variable is set.
Parameters:
- *args: Arguments to print to debug stream
Note: Only outputs when _ARC_DEBUG environment variable is present
"""def warn(*args) -> None:
"""
Print warning messages to stderr during completion.
Parameters:
- *args: Warning messages to display
This interrupts the user's command line interaction and should only
be used to indicate error conditions preventing completion.
"""Usage:
# Enable debug output
export _ARC_DEBUG=1
my-script --<TAB> # Shows debug information# In custom completers
from argcomplete import debug, warn
class MyCompleter(BaseCompleter):
def __call__(self, prefix, **kwargs):
debug("MyCompleter called with prefix:", prefix)
try:
completions = self._get_completions(prefix)
debug("Generated completions:", completions)
return completions
except Exception as e:
warn(f"Completion failed: {e}")
return []Context manager for suppressing stderr during completion operations.
@contextlib.contextmanager
def mute_stderr():
"""
Context manager to temporarily suppress stderr.
Used internally to prevent argparse error messages during completion.
"""Usage:
from argcomplete import mute_stderr
# Suppress error output during completion parsing
with mute_stderr():
try:
parser.parse_args(incomplete_args)
except SystemExit:
pass # Expected during completionNote: mute_stdout is available in argcomplete.io but not exported in the main public API.
Set of argparse action classes that are safe to execute during completion.
safe_actions: Set[Type[argparse.Action]]Usage:
from argcomplete import safe_actions
import argparse
# Check if an action is safe to execute during completion
def is_safe_action(action):
return action.__class__ in safe_actions
# Add custom safe actions
class MyCustomAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, values)
safe_actions.add(MyCustomAction)Utility for parsing command lines while respecting shell quoting and word boundaries.
def split_line(line: str, point: Optional[int] = None) -> Tuple[str, str, str, List[str], Optional[int]]:
"""
Split command line respecting shell quoting and word boundaries.
Parameters:
- line: Command line string to split
- point: Cursor position in the line (default: end of line)
Returns:
- Tuple containing:
- cword_prequote: Quote character before current word
- cword_prefix: Prefix of current word being completed
- cword_suffix: Suffix of current word after cursor
- comp_words: List of complete words before current position
- last_wordbreak_pos: Position of last word break character
"""Usage:
from argcomplete import split_line
# Parse a command line
line = 'my-script --config "path with spaces" --output'
point = len(line) # Cursor at end
prequote, prefix, suffix, words, wordbreak_pos = split_line(line, point)
print(f"Prequote: {repr(prequote)}")
print(f"Prefix: {repr(prefix)}")
print(f"Suffix: {repr(suffix)}")
print(f"Words: {words}")
print(f"Wordbreak position: {wordbreak_pos}")Note: The following are suggested utility functions you can implement in your own code. These are not part of the argcomplete API but are common patterns for working with completion environments.
Check for completion environment and get debug status:
import os
def is_completion_active():
"""Check if currently running in completion mode."""
return "_ARGCOMPLETE" in os.environ
def is_debug_enabled():
"""Check if debug output is enabled."""
return "_ARC_DEBUG" in os.environ
# Usage in custom code
if is_completion_active():
# Special behavior during completion
return get_completions_quickly()
else:
# Normal execution
return process_normally()Detect the shell environment during completion:
import os
def get_completion_shell():
"""Get the shell being used for completion."""
return os.environ.get("_ARGCOMPLETE_SHELL", "unknown")
def is_zsh_completion():
"""Check if completion is running under zsh."""
return get_completion_shell() == "zsh"
def is_bash_completion():
"""Check if completion is running under bash."""
return get_completion_shell() == "bash"
# Usage
shell = get_completion_shell()
if shell == "zsh":
# ZSH supports descriptions
return {"option": "description"}
else:
# Other shells
return ["option"]Extract completion-specific data from the environment:
import os
def get_completion_line():
"""Get the full command line being completed."""
return os.environ.get("COMP_LINE", "")
def get_completion_point():
"""Get cursor position in the command line."""
return int(os.environ.get("COMP_POINT", 0))
def get_completion_type():
"""Get the type of completion being performed."""
return os.environ.get("COMP_TYPE", "")
# Usage in advanced completers
class AdvancedCompleter(BaseCompleter):
def __call__(self, prefix, **kwargs):
comp_line = get_completion_line()
comp_point = get_completion_point()
# Analyze full command line for context
if "--verbose" in comp_line:
return self._get_verbose_completions(prefix)
else:
return self._get_normal_completions(prefix)from argcomplete import debug
import os
def debug_completion_state():
"""Output comprehensive debug information."""
debug("=== Completion Debug Info ===")
debug("COMP_LINE:", os.environ.get("COMP_LINE"))
debug("COMP_POINT:", os.environ.get("COMP_POINT"))
debug("Shell:", os.environ.get("_ARGCOMPLETE_SHELL"))
debug("Args:", sys.argv)
debug("===========================")
# Use at start of completion
if "_ARC_DEBUG" in os.environ:
debug_completion_state()from argcomplete import warn
def safe_completion_wrapper(func):
"""Decorator to safely handle completion errors."""
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
warn(f"Completion error in {func.__name__}: {e}")
return []
return wrapper
# Use with custom completers
@safe_completion_wrapper
def my_completion_function(prefix):
# Potentially error-prone completio logic
return risky_completion_logic(prefix)import time
from argcomplete import debug
def timed_completion(func):
"""Decorator to monitor completion performance."""
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
elapsed = time.time() - start_time
debug(f"Completion took {elapsed:.3f}s")
return result
return wrapper
# Monitor completion performance
@timed_completion
def slow_completer(prefix):
# Completion logic that might be slow
return expensive_completion_logic(prefix)Install with Tessl CLI
npx tessl i tessl/pypi-argcomplete