Bash tab completion for argparse
npx @tessl/cli install tessl/pypi-argcomplete@3.6.00
# Argcomplete
1
2
Argcomplete provides powerful bash/zsh tab completion for Python applications using argparse. It enables developers to add interactive command-line completion capabilities to their Python scripts and applications, supporting both static and dynamic completion scenarios with custom completers, choice validation, environment variable integration, and real-time API-based completions.
3
4
## Package Information
5
6
- **Package Name**: argcomplete
7
- **Language**: Python
8
- **Installation**: `pip install argcomplete`
9
10
## Core Imports
11
12
```python
13
import argcomplete
14
```
15
16
For most use cases:
17
18
```python
19
from argcomplete import autocomplete
20
```
21
22
For specific completers:
23
24
```python
25
from argcomplete import ChoicesCompleter, FilesCompleter, DirectoriesCompleter
26
```
27
28
## Basic Usage
29
30
```python
31
#!/usr/bin/env python
32
# PYTHON_ARGCOMPLETE_OK
33
34
import argparse
35
import argcomplete
36
37
# Create argument parser
38
parser = argparse.ArgumentParser(description='My CLI tool')
39
parser.add_argument('--name', help='Name to greet')
40
parser.add_argument('--config', type=argparse.FileType('r'),
41
help='Configuration file')
42
43
# Enable argcomplete
44
argcomplete.autocomplete(parser)
45
46
# Parse arguments normally
47
args = parser.parse_args()
48
print(f"Hello, {args.name}!")
49
```
50
51
Then register the script for completion:
52
53
```bash
54
eval "$(register-python-argcomplete my-script.py)"
55
```
56
57
## Architecture
58
59
Argcomplete uses a patching mechanism to intercept argparse operations during completion:
60
61
- **CompletionFinder**: Core engine that patches argparse parsers to collect completion candidates
62
- **Completers**: Pluggable completion strategies (files, choices, directories, environment variables)
63
- **Shell Integration**: Generated shell code that interfaces with the completion system
64
- **Lexers**: Command line parsing utilities that respect shell quoting and word boundaries
65
66
The system activates only when shell completion environment variables are present, allowing scripts to function normally during regular execution while providing rich completion during tab completion.
67
68
## Capabilities
69
70
### Core Completion Engine
71
72
The main completion system that provides the primary interface for enabling tab completion in Python scripts using argparse.
73
74
```python { .api }
75
autocomplete: CompletionFinder # Pre-instantiated completion finder
76
77
# Usage: autocomplete(parser, **kwargs) calls CompletionFinder.__call__()
78
```
79
80
```python { .api }
81
class CompletionFinder:
82
def __init__(
83
self,
84
argument_parser=None,
85
always_complete_options=True,
86
exclude=None,
87
validator=None,
88
print_suppressed=False,
89
default_completer=FilesCompleter(),
90
append_space=None
91
)
92
93
def __call__(
94
self,
95
argument_parser: argparse.ArgumentParser,
96
always_complete_options: Union[bool, str] = True,
97
exit_method: Callable = os._exit,
98
output_stream: Optional[TextIO] = None,
99
exclude: Optional[Sequence[str]] = None,
100
validator: Optional[Callable] = None,
101
print_suppressed: bool = False,
102
append_space: Optional[bool] = None,
103
default_completer: BaseCompleter = FilesCompleter()
104
) -> None
105
```
106
107
[Core Completion Engine](./completion-engine.md)
108
109
### Completers
110
111
Built-in completer classes that provide different completion strategies for various argument types, including file paths, directories, predefined choices, and environment variables.
112
113
```python { .api }
114
class BaseCompleter:
115
def __call__(
116
self,
117
*,
118
prefix: str,
119
action: argparse.Action,
120
parser: argparse.ArgumentParser,
121
parsed_args: argparse.Namespace
122
) -> None
123
```
124
125
```python { .api }
126
class ChoicesCompleter(BaseCompleter):
127
def __init__(self, choices)
128
def __call__(self, **kwargs)
129
130
class FilesCompleter(BaseCompleter):
131
def __init__(self, allowednames=(), directories=True)
132
def __call__(self, prefix, **kwargs)
133
134
class DirectoriesCompleter(BaseCompleter):
135
def __init__(self)
136
137
class SuppressCompleter(BaseCompleter):
138
def __init__(self)
139
def suppress(self) -> bool
140
```
141
142
```python { .api }
143
EnvironCompleter: ChoicesCompleter # Pre-configured with os.environ
144
```
145
146
[Completers](./completers.md)
147
148
### Shell Integration
149
150
Functions for generating shell-specific completion code that can be sourced or registered with the shell's completion system.
151
152
```python { .api }
153
def shellcode(
154
executables: List[str],
155
use_defaults: bool = True,
156
shell: str = "bash",
157
complete_arguments: Optional[List[str]] = None,
158
argcomplete_script: Optional[str] = None
159
) -> str
160
```
161
162
[Shell Integration](./shell-integration.md)
163
164
### Utility Functions
165
166
Support functions for debugging, output control, and command line parsing during completion operations.
167
168
```python { .api }
169
def debug(*args) -> None
170
def warn(*args) -> None
171
def split_line(line: str, point: Optional[int] = None) -> Tuple[str, str, str, List[str], Optional[int]]
172
safe_actions: Set[Type[argparse.Action]]
173
```
174
175
[Utilities](./utilities.md)
176
177
### Command Line Scripts
178
179
Command-line utilities for registering and activating argcomplete completion for Python scripts globally or individually.
180
181
Entry points available after installation:
182
183
- `register-python-argcomplete` - Register individual scripts
184
- `activate-global-python-argcomplete` - Enable global completion
185
- `python-argcomplete-check-easy-install-script` - Validate easy install scripts
186
187
[Command Line Scripts](./scripts.md)
188
189
## Types
190
191
```python { .api }
192
class ArgcompleteException(Exception):
193
"""Exception raised when the shell argument completion process fails."""
194
195
class ExclusiveCompletionFinder(CompletionFinder):
196
"""Variant of CompletionFinder that provides exclusive completion behavior."""
197
```