README.rst 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. argcomplete - Bash/zsh tab completion for argparse
  2. ==================================================
  3. *Tab complete all the things!*
  4. Argcomplete provides easy, extensible command line tab completion of arguments for your Python application.
  5. It makes two assumptions:
  6. * You're using bash or zsh as your shell
  7. * You're using `argparse <http://docs.python.org/3/library/argparse.html>`_ to manage your command line arguments/options
  8. Argcomplete is particularly useful if your program has lots of options or subparsers, and if your program can
  9. dynamically suggest completions for your argument/option values (for example, if the user is browsing resources over
  10. the network).
  11. Installation
  12. ------------
  13. ::
  14. pip install argcomplete
  15. activate-global-python-argcomplete
  16. See `Activating global completion`_ below for details about the second step.
  17. Refresh your shell environment (start a new shell).
  18. Synopsis
  19. --------
  20. Add the ``PYTHON_ARGCOMPLETE_OK`` marker and a call to ``argcomplete.autocomplete()`` to your Python application as
  21. follows:
  22. .. code-block:: python
  23. #!/usr/bin/env python
  24. # PYTHON_ARGCOMPLETE_OK
  25. import argcomplete, argparse
  26. parser = argparse.ArgumentParser()
  27. ...
  28. argcomplete.autocomplete(parser)
  29. args = parser.parse_args()
  30. ...
  31. If using ``pyproject.toml`` ``[project.scripts]`` entry points, the ``PYTHON_ARGCOMPLETE_OK`` marker should appear
  32. at the beginning of the file that contains the entry point.
  33. Register your Python application with your shell's completion framework by running ``register-python-argcomplete``::
  34. eval "$(register-python-argcomplete my-python-app)"
  35. Quotes are significant; the registration will fail without them. See `Global completion`_ below for a way to enable
  36. argcomplete generally without registering each application individually.
  37. argcomplete.autocomplete(*parser*)
  38. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  39. This method is the entry point to the module. It must be called **after** ArgumentParser construction is complete, but
  40. **before** the ``ArgumentParser.parse_args()`` method is called. The method looks for an environment variable that the
  41. completion hook shellcode sets, and if it's there, collects completions, prints them to the output stream (fd 8 by
  42. default), and exits. Otherwise, it returns to the caller immediately.
  43. .. admonition:: Side effects
  44. Argcomplete gets completions by running your program. It intercepts the execution flow at the moment
  45. ``argcomplete.autocomplete()`` is called. After sending completions, it exits using ``exit_method`` (``os._exit``
  46. by default). This means if your program has any side effects that happen before ``argcomplete`` is called, those
  47. side effects will happen every time the user presses ``<TAB>`` (although anything your program prints to stdout or
  48. stderr will be suppressed). For this reason it's best to construct the argument parser and call
  49. ``argcomplete.autocomplete()`` as early as possible in your execution flow.
  50. .. admonition:: Performance
  51. If the program takes a long time to get to the point where ``argcomplete.autocomplete()`` is called, the tab completion
  52. process will feel sluggish, and the user may lose confidence in it. So it's also important to minimize the startup time
  53. of the program up to that point (for example, by deferring initialization or importing of large modules until after
  54. parsing options).
  55. Specifying completers
  56. ---------------------
  57. You can specify custom completion functions for your options and arguments. Two styles are supported: callable and
  58. readline-style. Callable completers are simpler. They are called with the following keyword arguments:
  59. * ``prefix``: The prefix text of the last word before the cursor on the command line.
  60. For dynamic completers, this can be used to reduce the work required to generate possible completions.
  61. * ``action``: The ``argparse.Action`` instance that this completer was called for.
  62. * ``parser``: The ``argparse.ArgumentParser`` instance that the action was taken by.
  63. * ``parsed_args``: The result of argument parsing so far (the ``argparse.Namespace`` args object normally returned by
  64. ``ArgumentParser.parse_args()``).
  65. Completers can return their completions as an iterable of strings or a mapping (dict) of strings to their
  66. descriptions (zsh will display the descriptions as context help alongside completions). An example completer for names
  67. of environment variables might look like this:
  68. .. code-block:: python
  69. def EnvironCompleter(**kwargs):
  70. return os.environ
  71. To specify a completer for an argument or option, set the ``completer`` attribute of its associated action. An easy
  72. way to do this at definition time is:
  73. .. code-block:: python
  74. from argcomplete.completers import EnvironCompleter
  75. parser = argparse.ArgumentParser()
  76. parser.add_argument("--env-var1").completer = EnvironCompleter
  77. parser.add_argument("--env-var2").completer = EnvironCompleter
  78. argcomplete.autocomplete(parser)
  79. If you specify the ``choices`` keyword for an argparse option or argument (and don't specify a completer), it will be
  80. used for completions.
  81. A completer that is initialized with a set of all possible choices of values for its action might look like this:
  82. .. code-block:: python
  83. class ChoicesCompleter(object):
  84. def __init__(self, choices):
  85. self.choices = choices
  86. def __call__(self, **kwargs):
  87. return self.choices
  88. The following two ways to specify a static set of choices are equivalent for completion purposes:
  89. .. code-block:: python
  90. from argcomplete.completers import ChoicesCompleter
  91. parser.add_argument("--protocol", choices=('http', 'https', 'ssh', 'rsync', 'wss'))
  92. parser.add_argument("--proto").completer=ChoicesCompleter(('http', 'https', 'ssh', 'rsync', 'wss'))
  93. Note that if you use the ``choices=<completions>`` option, argparse will show
  94. all these choices in the ``--help`` output by default. To prevent this, set
  95. ``metavar`` (like ``parser.add_argument("--protocol", metavar="PROTOCOL",
  96. choices=('http', 'https', 'ssh', 'rsync', 'wss'))``).
  97. The following `script <https://raw.github.com/kislyuk/argcomplete/master/docs/examples/describe_github_user.py>`_ uses
  98. ``parsed_args`` and `Requests <http://python-requests.org/>`_ to query GitHub for publicly known members of an
  99. organization and complete their names, then prints the member description:
  100. .. code-block:: python
  101. #!/usr/bin/env python
  102. # PYTHON_ARGCOMPLETE_OK
  103. import argcomplete, argparse, requests, pprint
  104. def github_org_members(prefix, parsed_args, **kwargs):
  105. resource = "https://api.github.com/orgs/{org}/members".format(org=parsed_args.organization)
  106. return (member['login'] for member in requests.get(resource).json() if member['login'].startswith(prefix))
  107. parser = argparse.ArgumentParser()
  108. parser.add_argument("--organization", help="GitHub organization")
  109. parser.add_argument("--member", help="GitHub member").completer = github_org_members
  110. argcomplete.autocomplete(parser)
  111. args = parser.parse_args()
  112. pprint.pprint(requests.get("https://api.github.com/users/{m}".format(m=args.member)).json())
  113. `Try it <https://raw.github.com/kislyuk/argcomplete/master/docs/examples/describe_github_user.py>`_ like this::
  114. ./describe_github_user.py --organization heroku --member <TAB>
  115. If you have a useful completer to add to the `completer library
  116. <https://github.com/kislyuk/argcomplete/blob/master/argcomplete/completers.py>`_, send a pull request!
  117. Readline-style completers
  118. ~~~~~~~~~~~~~~~~~~~~~~~~~
  119. The readline_ module defines a completer protocol in rlcompleter_. Readline-style completers are also supported by
  120. argcomplete, so you can use the same completer object both in an interactive readline-powered shell and on the command
  121. line. For example, you can use the readline-style completer provided by IPython_ to get introspective completions like
  122. you would get in the IPython shell:
  123. .. _readline: http://docs.python.org/3/library/readline.html
  124. .. _rlcompleter: http://docs.python.org/3/library/rlcompleter.html#completer-objects
  125. .. _IPython: http://ipython.org/
  126. .. code-block:: python
  127. import IPython
  128. parser.add_argument("--python-name").completer = IPython.core.completer.Completer()
  129. ``argcomplete.CompletionFinder.rl_complete`` can also be used to plug in an argparse parser as a readline completer.
  130. Printing warnings in completers
  131. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  132. Normal stdout/stderr output is suspended when argcomplete runs. Sometimes, though, when the user presses ``<TAB>``, it's
  133. appropriate to print information about why completions generation failed. To do this, use ``warn``:
  134. .. code-block:: python
  135. from argcomplete import warn
  136. def AwesomeWebServiceCompleter(prefix, **kwargs):
  137. if login_failed:
  138. warn("Please log in to Awesome Web Service to use autocompletion")
  139. return completions
  140. Using a custom completion validator
  141. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  142. By default, argcomplete validates your completions by checking if they start with the prefix given to the completer. You
  143. can override this validation check by supplying the ``validator`` keyword to ``argcomplete.autocomplete()``:
  144. .. code-block:: python
  145. def my_validator(completion_candidate, current_input):
  146. """Complete non-prefix substring matches."""
  147. return current_input in completion_candidate
  148. argcomplete.autocomplete(parser, validator=my_validator)
  149. Global completion
  150. -----------------
  151. In global completion mode, you don't have to register each argcomplete-capable executable separately. Instead, the shell
  152. will look for the string **PYTHON_ARGCOMPLETE_OK** in the first 1024 bytes of any executable that it's running
  153. completion for, and if it's found, follow the rest of the argcomplete protocol as described above.
  154. Additionally, completion is activated for scripts run as ``python <script>`` and ``python -m <module>``. If you're using
  155. multiple Python versions on the same system, the version being used to run the script must have argcomplete installed.
  156. .. admonition:: Bash version compatibility
  157. When using bash, global completion requires bash support for ``complete -D``, which was introduced in bash 4.2. Since
  158. Mac OS ships with an outdated version of Bash (3.2), you can either use zsh or install a newer version of bash using
  159. `Homebrew <http://brew.sh/>`_ (``brew install bash`` - you will also need to add ``/opt/homebrew/bin/bash`` to
  160. ``/etc/shells``, and run ``chsh`` to change your shell). You can check the version of the running copy of bash with
  161. ``echo $BASH_VERSION``.
  162. .. note:: If you use ``project.scripts`` directives to provide command line entry points to your package,
  163. argcomplete will follow the wrapper scripts to their destination and look for ``PYTHON_ARGCOMPLETE_OK`` in the
  164. first kilobyte of the file containing the destination code.
  165. If you choose not to use global completion, or ship a completion module that depends on argcomplete, you must register
  166. your script explicitly using ``eval "$(register-python-argcomplete my-python-app)"``. Standard completion module
  167. registration rules apply: namely, the script name is passed directly to ``complete``, meaning it is only tab completed
  168. when invoked exactly as it was registered. In the above example, ``my-python-app`` must be on the path, and the user
  169. must be attempting to complete it by that name. The above line alone would **not** allow you to complete
  170. ``./my-python-app``, or ``/path/to/my-python-app``.
  171. Activating global completion
  172. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  173. The script ``activate-global-python-argcomplete`` installs the global completion script
  174. `bash_completion.d/_python-argcomplete <https://github.com/kislyuk/argcomplete/blob/master/argcomplete/bash_completion.d/_python-argcomplete>`_
  175. into an appropriate location on your system for both bash and zsh. The specific location depends on your platform and
  176. whether you installed argcomplete system-wide using ``sudo`` or locally (into your user's home directory).
  177. Zsh Support
  178. -----------
  179. Argcomplete supports zsh. On top of plain completions like in bash, zsh allows you to see argparse help strings as
  180. completion descriptions. All shellcode included with argcomplete is compatible with both bash and zsh, so the same
  181. completer commands ``activate-global-python-argcomplete`` and ``eval "$(register-python-argcomplete my-python-app)"``
  182. work for zsh as well.
  183. Python Support
  184. --------------
  185. Argcomplete requires Python 3.7+.
  186. Support for other shells
  187. ------------------------
  188. Argcomplete maintainers provide support only for the bash and zsh shells on Linux and MacOS. For resources related to
  189. other shells and platforms, including fish, tcsh, xonsh, powershell, and Windows, please see the
  190. `contrib <https://github.com/kislyuk/argcomplete/tree/develop/contrib>`_ directory.
  191. Common Problems
  192. ---------------
  193. If global completion is not completing your script, bash may have registered a default completion function::
  194. $ complete | grep my-python-app
  195. complete -F _minimal my-python-app
  196. You can fix this by restarting your shell, or by running ``complete -r my-python-app``.
  197. Debugging
  198. ---------
  199. Set the ``_ARC_DEBUG`` variable in your shell to enable verbose debug output every time argcomplete runs. This will
  200. disrupt the command line composition state of your terminal, but make it possible to see the internal state of the
  201. completer if it encounters problems.
  202. Acknowledgments
  203. ---------------
  204. Inspired and informed by the optcomplete_ module by Martin Blais.
  205. .. _optcomplete: http://pypi.python.org/pypi/optcomplete
  206. Links
  207. -----
  208. * `Project home page (GitHub) <https://github.com/kislyuk/argcomplete>`_
  209. * `Documentation <https://kislyuk.github.io/argcomplete/>`_
  210. * `Package distribution (PyPI) <https://pypi.python.org/pypi/argcomplete>`_
  211. * `Change log <https://github.com/kislyuk/argcomplete/blob/master/Changes.rst>`_
  212. Bugs
  213. ~~~~
  214. Please report bugs, issues, feature requests, etc. on `GitHub <https://github.com/kislyuk/argcomplete/issues>`_.
  215. License
  216. -------
  217. Copyright 2012-2023, Andrey Kislyuk and argcomplete contributors. Licensed under the terms of the
  218. `Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0>`_. Distribution of the LICENSE and NOTICE
  219. files with source copies of this package and derivative works is **REQUIRED** as specified by the Apache License.
  220. .. image:: https://github.com/kislyuk/argcomplete/workflows/Python%20package/badge.svg
  221. :target: https://github.com/kislyuk/argcomplete/actions
  222. .. image:: https://codecov.io/github/kislyuk/argcomplete/coverage.svg?branch=master
  223. :target: https://codecov.io/github/kislyuk/argcomplete?branch=master
  224. .. image:: https://img.shields.io/pypi/v/argcomplete.svg
  225. :target: https://pypi.python.org/pypi/argcomplete
  226. .. image:: https://img.shields.io/pypi/l/argcomplete.svg
  227. :target: https://pypi.python.org/pypi/argcomplete