README.rst 14 KB

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