Package: argcomplete
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 shellYou’re usingargparseto manage your command line arguments/optionsArgcomplete 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).Installationpip install argcomplete
activate-global-python-argcompleteSeeActivating global completionbelow for details about the second step.Refresh your shell environment (start a new shell).SynopsisAdd thePYTHON_ARGCOMPLETE_OKmarker and a call toargcomplete.autocomplete()to your Python application as
follows:#!/usr/bin/env python# PYTHON_ARGCOMPLETE_OKimportargcomplete,argparseparser=argparse.ArgumentParser()...argcomplete.autocomplete(parser)args=parser.parse_args()...Register your Python application with your shell’s completion framework by runningregister-python-argcomplete:eval "$(register-python-argcomplete my-python-app)"Quotes are significant; the registration will fail without them. SeeGlobal completionbelow 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 calledafterArgumentParser construction is complete, butbeforetheArgumentParser.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 effectsArgcomplete gets completions by running your program. It intercepts the execution flow at the momentargcomplete.autocomplete()is called. After sending completions, it exits usingexit_method(os._exitby default). This means if your program has any side effects that happen beforeargcompleteis 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 callargcomplete.autocomplete()as early as possible in your execution flow.PerformanceIf the program takes a long time to get to the point whereargcomplete.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 completersYou 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.Actioninstance that this completer was called for.parser: Theargparse.ArgumentParserinstance that the action was taken by.parsed_args: The result of argument parsing so far (theargparse.Namespaceargs 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:defEnvironCompleter(**kwargs):returnos.environTo specify a completer for an argument or option, set thecompleterattribute of its associated action. An easy
way to do this at definition time is:fromargcomplete.completersimportEnvironCompleterparser=argparse.ArgumentParser()parser.add_argument("--env-var1").completer=EnvironCompleterparser.add_argument("--env-var2").completer=EnvironCompleterargcomplete.autocomplete(parser)If you specify thechoiceskeyword 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:classChoicesCompleter(object):def__init__(self,choices):self.choices=choicesdef__call__(self,**kwargs):returnself.choicesThe following two ways to specify a static set of choices are equivalent for completion purposes:fromargcomplete.completersimportChoicesCompleterparser.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 thechoices=<completions>option, argparse will show
all these choices in the--helpoutput by default. To prevent this, setmetavar(likeparser.add_argument("--protocol",metavar="PROTOCOL",choices=('http','https', 'ssh', 'rsync','wss'))).The followingscriptusesparsed_argsandRequeststo query GitHub for publicly known members of an
organization and complete their names, then prints the member description:#!/usr/bin/env python# PYTHON_ARGCOMPLETE_OKimportargcomplete,argparse,requests,pprintdefgithub_org_members(prefix,parsed_args,**kwargs):resource="https://api.github.com/orgs/{org}/members".format(org=parsed_args.organization)return(member['login']formemberinrequests.get(resource).json()ifmember['login'].startswith(prefix))parser=argparse.ArgumentParser()parser.add_argument("--organization",help="GitHub organization")parser.add_argument("--member",help="GitHub member").completer=github_org_membersargcomplete.autocomplete(parser)args=parser.parse_args()pprint.pprint(requests.get("https://api.github.com/users/{m}".format(m=args.member)).json())Try itlike this:./describe_github_user.py --organization heroku --member <TAB>If you have a useful completer to add to thecompleter library, send a pull request!Readline-style completersThereadlinemodule defines a completer protocol inrlcompleter. 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 byIPythonto get introspective completions like
you would get in the IPython shell:importIPythonparser.add_argument("--python-name").completer=IPython.core.completer.Completer()argcomplete.CompletionFinder.rl_completecan also be used to plug in an argparse parser as a readline completer.Printing warnings in completersNormal 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, usewarn:fromargcompleteimportwarndefAwesomeWebServiceCompleter(prefix,**kwargs):iflogin_failed:warn("Please log in to Awesome Web Service to use autocompletion")returncompletionsUsing a custom completion validatorBy 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 thevalidatorkeyword toargcomplete.autocomplete():defmy_validator(completion_candidate,current_input):"""Complete non-prefix substring matches."""returncurrent_inputincompletion_candidateargcomplete.autocomplete(parser,validator=my_validator)Global completionIn global completion mode, you don’t have to register each argcomplete-capable executable separately. Instead, the shell
will look for the stringPYTHON_ARGCOMPLETE_OKin 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 aspython <script>andpython-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 compatibilityWhen using bash, global completion requires bash support forcomplete-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 usingHomebrew(brew install bash- you will also need to add/opt/homebrew/bin/bashto/etc/shells, and runchshto change your shell). You can check the version of the running copy of bash withecho $BASH_VERSION.NoteIf you use setuptools/distributescriptsorentry_pointsdirectives to package your module,
argcomplete will follow the wrapper scripts to their destination and look forPYTHON_ARGCOMPLETE_OKin 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 usingeval"$(register-python-argcompletemy-python-app)". Standard completion module
registration rules apply: namely, the script name is passed directly tocomplete, meaning it is only tab completed
when invoked exactly as it was registered. In the above example,my-python-appmust be on the path, and the user
must be attempting to complete it by that name. The above line alone wouldnotallow you to complete./my-python-app, or/path/to/my-python-app.Activating global completionThe scriptactivate-global-python-argcompleteinstalls the global completion scriptbash_completion.d/_python-argcompleteinto 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 usingsudoor locally (into your user’s home directory).Zsh SupportArgcomplete 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 commandsactivate-global-python-argcompleteandeval"$(register-python-argcompletemy-python-app)"work for zsh as well.Python SupportArgcomplete requires Python 3.7+.Support for other shellsArgcomplete 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 thecontribdirectory.Common ProblemsIf 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-appYou can fix this by restarting your shell, or by runningcomplete-rmy-python-app.DebuggingSet the_ARC_DEBUGvariable 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.AcknowledgmentsInspired and informed by theoptcompletemodule by Martin Blais.LinksProject home page (GitHub)DocumentationPackage distribution (PyPI)Change logBugsPlease report bugs, issues, feature requests, etc. onGitHub.LicenseCopyright 2012-2023, Andrey Kislyuk and argcomplete contributors. Licensed under the terms of theApache License, Version 2.0. Distribution of the LICENSE and NOTICE
files with source copies of this package and derivative works isREQUIREDas specified by the Apache License.