argcomplete - Bash/zsh tab completion for argparse¶
Tab complete all the things!
Argcomplete provides easy, extensible command line tab completion of arguments for your Python application.
It makes two assumptions:
You’re using bash or zsh as your shell
You’re using argparse to manage your command line arguments/options
Argcomplete is particularly useful if your program has lots of options or subparsers, and if your program can dynamically suggest completions for your argument/option values (for example, if the user is browsing resources over the network).
Installation¶
pip install argcomplete
activate-global-python-argcomplete
See Activating global completion below for details about the second step.
Refresh your shell environment (start a new shell).
Synopsis¶
Add the PYTHON_ARGCOMPLETE_OK
marker and a call to argcomplete.autocomplete()
to your Python application as
follows:
#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
import argcomplete, argparse
parser = argparse.ArgumentParser()
...
argcomplete.autocomplete(parser)
args = parser.parse_args()
...
Register your Python application with your shell’s completion framework by running register-python-argcomplete
:
eval "$(register-python-argcomplete my-python-app)"
Quotes are significant; the registration will fail without them. See Global completion below for a way to enable argcomplete generally without registering each application individually.
argcomplete.autocomplete(parser)¶
This method is the entry point to the module. It must be called after ArgumentParser construction is complete, but
before the ArgumentParser.parse_args()
method is called. The method looks for an environment variable that the
completion hook shellcode sets, and if it’s there, collects completions, prints them to the output stream (fd 8 by
default), and exits. Otherwise, it returns to the caller immediately.
Side effects
Argcomplete gets completions by running your program. It intercepts the execution flow at the moment
argcomplete.autocomplete()
is called. After sending completions, it exits using exit_method
(os._exit
by default). This means if your program has any side effects that happen before argcomplete
is called, those
side effects will happen every time the user presses <TAB>
(although anything your program prints to stdout or
stderr will be suppressed). For this reason it’s best to construct the argument parser and call
argcomplete.autocomplete()
as early as possible in your execution flow.
Performance
If the program takes a long time to get to the point where argcomplete.autocomplete()
is called, the tab completion
process will feel sluggish, and the user may lose confidence in it. So it’s also important to minimize the startup time
of the program up to that point (for example, by deferring initialization or importing of large modules until after
parsing options).
Specifying completers¶
You can specify custom completion functions for your options and arguments. Two styles are supported: callable and readline-style. Callable completers are simpler. They are called with the following keyword arguments:
prefix
: The prefix text of the last word before the cursor on the command line. For dynamic completers, this can be used to reduce the work required to generate possible completions.action
: Theargparse.Action
instance that this completer was called for.parser
: Theargparse.ArgumentParser
instance that the action was taken by.parsed_args
: The result of argument parsing so far (theargparse.Namespace
args object normally returned byArgumentParser.parse_args()
).
Completers can return their completions as an iterable of strings or a mapping (dict) of strings to their descriptions (zsh will display the descriptions as context help alongside completions). An example completer for names of environment variables might look like this:
def EnvironCompleter(**kwargs):
return os.environ
To specify a completer for an argument or option, set the completer
attribute of its associated action. An easy
way to do this at definition time is:
from argcomplete.completers import EnvironCompleter
parser = argparse.ArgumentParser()
parser.add_argument("--env-var1").completer = EnvironCompleter
parser.add_argument("--env-var2").completer = EnvironCompleter
argcomplete.autocomplete(parser)
If you specify the choices
keyword for an argparse option or argument (and don’t specify a completer), it will be
used for completions.
A completer that is initialized with a set of all possible choices of values for its action might look like this:
class ChoicesCompleter(object):
def __init__(self, choices):
self.choices = choices
def __call__(self, **kwargs):
return self.choices
The following two ways to specify a static set of choices are equivalent for completion purposes:
from argcomplete.completers import ChoicesCompleter
parser.add_argument("--protocol", choices=('http', 'https', 'ssh', 'rsync', 'wss'))
parser.add_argument("--proto").completer=ChoicesCompleter(('http', 'https', 'ssh', 'rsync', 'wss'))
Note that if you use the choices=<completions>
option, argparse will show
all these choices in the --help
output by default. To prevent this, set
metavar
(like parser.add_argument("--protocol", metavar="PROTOCOL",
choices=('http', 'https', 'ssh', 'rsync', 'wss'))
).
The following script uses
parsed_args
and Requests to query GitHub for publicly known members of an
organization and complete their names, then prints the member description:
#!/usr/bin/env python
# PYTHON_ARGCOMPLETE_OK
import argcomplete, argparse, requests, pprint
def github_org_members(prefix, parsed_args, **kwargs):
resource = "https://api.github.com/orgs/{org}/members".format(org=parsed_args.organization)
return (member['login'] for member in requests.get(resource).json() if member['login'].startswith(prefix))
parser = argparse.ArgumentParser()
parser.add_argument("--organization", help="GitHub organization")
parser.add_argument("--member", help="GitHub member").completer = github_org_members
argcomplete.autocomplete(parser)
args = parser.parse_args()
pprint.pprint(requests.get("https://api.github.com/users/{m}".format(m=args.member)).json())
Try it like this:
./describe_github_user.py --organization heroku --member <TAB>
If you have a useful completer to add to the completer library, send a pull request!
Readline-style completers¶
The readline module defines a completer protocol in rlcompleter_. Readline-style completers are also supported by argcomplete, so you can use the same completer object both in an interactive readline-powered shell and on the command line. For example, you can use the readline-style completer provided by IPython to get introspective completions like you would get in the IPython shell:
import IPython
parser.add_argument("--python-name").completer = IPython.core.completer.Completer()
argcomplete.CompletionFinder.rl_complete
can also be used to plug in an argparse parser as a readline completer.
Printing warnings in completers¶
Normal stdout/stderr output is suspended when argcomplete runs. Sometimes, though, when the user presses <TAB>
, it’s
appropriate to print information about why completions generation failed. To do this, use warn
:
from argcomplete import warn
def AwesomeWebServiceCompleter(prefix, **kwargs):
if login_failed:
warn("Please log in to Awesome Web Service to use autocompletion")
return completions
Using a custom completion validator¶
By default, argcomplete validates your completions by checking if they start with the prefix given to the completer. You
can override this validation check by supplying the validator
keyword to argcomplete.autocomplete()
:
def my_validator(completion_candidate, current_input):
"""Complete non-prefix substring matches."""
return current_input in completion_candidate
argcomplete.autocomplete(parser, validator=my_validator)
Global completion¶
In global completion mode, you don’t have to register each argcomplete-capable executable separately. Instead, the shell will look for the string PYTHON_ARGCOMPLETE_OK in the first 1024 bytes of any executable that it’s running completion for, and if it’s found, follow the rest of the argcomplete protocol as described above.
Additionally, completion is activated for scripts run as python <script>
and python -m <module>
. If you’re using
multiple Python versions on the same system, the version being used to run the script must have argcomplete installed.
Bash version compatibility
When using bash, global completion requires bash support for complete -D
, which was introduced in bash 4.2. Since
Mac OS ships with an outdated version of Bash (3.2), you can either use zsh or install a newer version of bash using
Homebrew (brew install bash
- you will also need to add /opt/homebrew/bin/bash
to
/etc/shells
, and run chsh
to change your shell). You can check the version of the running copy of bash with
echo $BASH_VERSION
.
Note
If you use setuptools/distribute scripts
or entry_points
directives to package your module,
argcomplete will follow the wrapper scripts to their destination and look for PYTHON_ARGCOMPLETE_OK
in the
destination code.
If you choose not to use global completion, or ship a completion module that depends on argcomplete, you must register
your script explicitly using eval "$(register-python-argcomplete my-python-app)"
. Standard completion module
registration rules apply: namely, the script name is passed directly to complete
, meaning it is only tab completed
when invoked exactly as it was registered. In the above example, my-python-app
must be on the path, and the user
must be attempting to complete it by that name. The above line alone would not allow you to complete
./my-python-app
, or /path/to/my-python-app
.
Activating global completion¶
The script activate-global-python-argcomplete
installs the global completion script
bash_completion.d/_python-argcomplete
into an appropriate location on your system for both bash and zsh. The specific location depends on your platform and
whether you installed argcomplete system-wide using sudo
or locally (into your user’s home directory).
Zsh Support¶
Argcomplete supports zsh. On top of plain completions like in bash, zsh allows you to see argparse help strings as
completion descriptions. All shellcode included with argcomplete is compatible with both bash and zsh, so the same
completer commands activate-global-python-argcomplete
and eval "$(register-python-argcomplete my-python-app)"
work for zsh as well.
Python Support¶
Argcomplete requires Python 3.7+.
Support for other shells¶
Argcomplete maintainers provide support only for the bash and zsh shells on Linux and MacOS. For resources related to other shells and platforms, including fish, tcsh, xonsh, powershell, and Windows, please see the contrib directory.
Common Problems¶
If global completion is not completing your script, bash may have registered a default completion function:
$ complete | grep my-python-app
complete -F _minimal my-python-app
You can fix this by restarting your shell, or by running complete -r my-python-app
.
Debugging¶
Set the _ARC_DEBUG
variable in your shell to enable verbose debug output every time argcomplete runs. This will
disrupt the command line composition state of your terminal, but make it possible to see the internal state of the
completer if it encounters problems.
Acknowledgments¶
Inspired and informed by the optcomplete module by Martin Blais.
Links¶
Bugs¶
Please report bugs, issues, feature requests, etc. on GitHub.
License¶
Copyright 2012-2023, Andrey Kislyuk and argcomplete contributors. Licensed under the terms of the Apache License, Version 2.0. Distribution of the LICENSE and NOTICE files with source copies of this package and derivative works is REQUIRED as specified by the Apache License.
API documentation¶
- argcomplete.autocomplete(argument_parser, always_complete_options=True, exit_method=<built-in function _exit>, output_stream=None, exclude=None, validator=None, print_suppressed=False, append_space=None, default_completer=<argcomplete.completers.FilesCompleter object>)¶
Use this to access argcomplete. See
argcomplete.CompletionFinder.__call__()
.
- class argcomplete.FilesCompleter(allowednames=(), directories=True)[source]¶
File completer class, optionally takes a list of allowed extensions
- class argcomplete.SuppressCompleter[source]¶
A completer used to suppress the completion of specific arguments
- exception argcomplete.ArgcompleteException[source]¶
Exception raised when the shell argument completion process fails.
- class argcomplete.CompletionFinder(argument_parser=None, always_complete_options=True, exclude=None, validator=None, print_suppressed=False, default_completer=<argcomplete.completers.FilesCompleter object>, append_space=None)[source]¶
Inherit from this class if you wish to override any of the stages below. Otherwise, use
argcomplete.autocomplete()
directly (it’s a convenience instance of this class). It has the same signature asCompletionFinder.__call__()
.- __init__(argument_parser=None, always_complete_options=True, exclude=None, validator=None, print_suppressed=False, default_completer=<argcomplete.completers.FilesCompleter object>, append_space=None)[source]¶
- __call__(argument_parser, always_complete_options=True, exit_method=<built-in function _exit>, output_stream=None, exclude=None, validator=None, print_suppressed=False, append_space=None, default_completer=<argcomplete.completers.FilesCompleter object>)[source]¶
- Parameters:
argument_parser (ArgumentParser) – The argument parser to autocomplete on
always_complete_options (bool | str) – Controls the autocompletion of option strings if an option string opening character (normally
-
) has not been entered. IfTrue
(default), both short (-x
) and long (--x
) option strings will be suggested. IfFalse
, no option strings will be suggested. Iflong
, long options and short options with no long variant will be suggested. Ifshort
, short options and long options with no short variant will be suggested.exit_method (Callable) – Method used to stop the program after printing completions. Defaults to
os._exit()
. If you want to perform a normal exit that calls exit handlers, usesys.exit()
.exclude (Sequence[str] | None) – List of strings representing options to be omitted from autocompletion
validator (Callable | None) – Function to filter all completions through before returning (called with two string arguments, completion and prefix; return value is evaluated as a boolean)
print_suppressed (bool) – Whether or not to autocomplete options that have the
help=argparse.SUPPRESS
keyword argument set.append_space (bool | None) – Whether to append a space to unique matches. The default is
True
.
Note
If you are not subclassing CompletionFinder to override its behaviors, use
argcomplete.autocomplete()
directly. It has the same signature as this method.Produces tab completions for
argument_parser
. See module docs for more info.Argcomplete only executes actions if their class is known not to have side effects. Custom action classes can be added to argcomplete.safe_actions, if their values are wanted in the
parsed_args
completer argument, or their execution is otherwise desirable.
- collect_completions(active_parsers, parsed_args, cword_prefix)[source]¶
Visits the active parsers and their actions, executes their completers or introspects them to collect their option strings. Returns the resulting completions as a list of strings.
This method is exposed for overriding in subclasses; there is no need to use it directly.
- filter_completions(completions)[source]¶
De-duplicates completions and excludes those specified by
exclude
. Returns the filtered completions as a list.This method is exposed for overriding in subclasses; there is no need to use it directly.
- quote_completions(completions, cword_prequote, last_wordbreak_pos)[source]¶
If the word under the cursor started with a quote (as indicated by a nonempty
cword_prequote
), escapes occurrences of that quote character in the completions, and adds the quote to the beginning of each completion. Otherwise, escapes all characters that bash splits words on (COMP_WORDBREAKS
), and removes portions of completions before the first colon if (COMP_WORDBREAKS
) contains a colon.If there is only one completion, and it doesn’t end with a continuation character (
/
,:
, or=
), adds a space after the completion.This method is exposed for overriding in subclasses; there is no need to use it directly.
- rl_complete(text, state)[source]¶
Alternate entry point for using the argcomplete completer in a readline-based REPL. See also rlcompleter. Usage:
import argcomplete, argparse, readline parser = argparse.ArgumentParser() ... completer = argcomplete.CompletionFinder(parser) readline.set_completer_delims("") readline.set_completer(completer.rl_complete) readline.parse_and_bind("tab: complete") result = input("prompt> ")
- class argcomplete.ExclusiveCompletionFinder(argument_parser=None, always_complete_options=True, exclude=None, validator=None, print_suppressed=False, default_completer=<argcomplete.completers.FilesCompleter object>, append_space=None)[source]¶
- argcomplete.warn(*args)[source]¶
Prints args to standard error when running completions. This will interrupt the user’s command line interaction; use it to indicate an error condition that is preventing your completer from working.
- argcomplete.shellcode(executables, use_defaults=True, shell='bash', complete_arguments=None, argcomplete_script=None)[source]¶
Provide the shell code required to register a python executable for use with the argcomplete module.
- Parameters:
executables (list(str)) – Executables to be completed (when invoked exactly with this name)
use_defaults (bool) – Whether to fallback to readline’s default completion when no matches are generated (affects bash only)
shell (str) – Name of the shell to output code for
complete_arguments (list(str) or None) – Arguments to call complete with (affects bash only)
argcomplete_script (str or None) – Script to call complete with, if not the executable to complete. If supplied, will be used to complete all passed executables.
Change log¶
- Release Notes
- Changes for v3.5.1 (2024-10-06)
- Changes for v3.5.0 (2024-08-06)
- Changes for v3.4.0 (2024-06-16)
- Changes for v3.3.0 (2024-04-14)
- Changes for v3.2.3 (2024-03-07)
- Changes for v3.2.2 (2024-01-23)
- Changes for v3.2.1 (2023-12-10)
- Changes for v3.2.0 (2023-12-09)
- Changes for v3.1.6 (2023-11-12)
- Changes for v3.1.5 (2023-11-12)
- Changes for v3.1.4 (2023-11-01)
- Changes for v3.1.3 (2023-11-01)
- Changes for v3.1.3 (2023-11-01)
- Changes for v3.1.2 (2023-09-16)
- Changes for v3.1.1 (2023-06-11)
- Changes for v3.1.0 (2023-06-10)
- Changes for v3.0.8 (2023-04-23)
- Changes for v3.0.7 (2023-04-23)
- Changes for v3.0.6 (2023-04-22)
- Changes for v3.0.5 (2023-03-25)
- Changes for v3.0.4 (2023-03-21)
- Changes for v3.0.3 (2023-03-20)
- Changes for v3.0.2 (2023-03-19)
- Changes for v3.0.1 (2023-03-19)
- Changes for v3.0.0 (2023-03-19)
- Changes for v2.1.2 (2023-03-17)
- Changes for v2.1.1 (2023-03-06)
- Changes for v2.1.0 (2023-03-06)
- Changes for v2.0.6 (2023-03-06)
- Changes for v2.0.5 (2023-03-04)
- Changes for v2.0.4 (2023-03-04)
- Changes for v2.0.3 (2023-03-04)
- Changes for v2.0.2 (2023-03-04)
- Changes for v2.0.1 (2023-03-04)
- Changes for v2.0.0 (2022-01-03)
- Changes for v1.12.3 (2021-04-19)
- Changes for v1.12.2 (2020-11-23)
- Changes for v1.12.1 (2020-09-26)
- Changes for v1.11.1 (2020-01-14)
- Changes for v1.11.0 (2019-12-23)
- Changes for v1.10.3 (2019-11-26)
- Changes for v1.10.2 (2019-11-17)
- Changes for v1.10.1 (2019-11-16)
- Changes for v1.10.0 (2019-05-12)
- Changes for v1.9.5 (2019-04-02)
- Changes for v1.9.4 (2018-02-13)
- Changes for v1.9.3 (2017-11-16)
- Changes for v1.9.2 (2017-08-23)
- Changes for v1.9.1 (2017-08-23)
- Changes for v1.9.0 (2017-08-23)
- Changes for v1.8.2 (2017-01-26)
- Changes for v1.8.1 (2017-01-21)
- Changes for v1.8.0 (2017-01-19)
- Changes for v1.7.0 (2016-11-30)
- Changes for v1.6.0 (2016-10-20)
- Changes for v1.5.1 (2016-10-11)
- Changes for v1.5.0 (2016-10-11)
- Version 1.4.1 (2016-06-14)
- Version 1.4.0 (2016-06-10)
- Version 1.3.0 (2016-06-01)
- Version 1.2.0 (2016-05-25)
- Version 1.1.1 (2016-03-22)
- Version 1.1.0 (2016-02-21)
- Version 1.0.0 (2015-08-22)
- Version 0.9.0 (2015-07-03)
- Version 0.8.9 (2015-06-01)
- Version 0.8.8 (2015-05-01)
- Version 0.8.7 (2015-04-11)
- Version 0.8.6 (2015-04-11)
- Version 0.8.5 (2015-04-07)
- Version 0.8.4 (2014-12-11)
- Version 0.8.3 (2014-11-09)
- Version 0.8.2 (2014-11-03)
- Version 0.8.1 (2014-07-02)
- Version 0.8.0 (2014-04-07)
- Version 0.7.1 (2014-03-29)
- Version 0.7.0 (2014-01-19)
- Version 0.6.9 (2014-01-19)
- Version 0.6.8 (2014-01-18)