README.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. argcomplete - Bash 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 script.
  5. It makes two assumptions:
  6. * You're using bash as your shell (limited support for zsh, fish, and tcsh is available)
  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. pip3 install argcomplete
  15. activate-global-python-argcomplete
  16. See `Activating global completion`_ below for details about the second step (or if it reports an error).
  17. Refresh your bash environment (start a new shell or ``source /etc/profile``).
  18. Synopsis
  19. --------
  20. Python code (e.g. ``my-awesome-script``):
  21. .. code-block:: python
  22. #!/usr/bin/env python
  23. # PYTHON_ARGCOMPLETE_OK
  24. import argcomplete, argparse
  25. parser = argparse.ArgumentParser()
  26. ...
  27. argcomplete.autocomplete(parser)
  28. args = parser.parse_args()
  29. ...
  30. Shellcode (only necessary if global completion is not activated - see `Global completion`_ below), to be put in e.g. ``.bashrc``::
  31. eval "$(register-python-argcomplete my-awesome-script)"
  32. argcomplete.autocomplete(*parser*)
  33. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  34. This method is the entry point to the module. It must be called **after** ArgumentParser construction is complete, but
  35. **before** the ``ArgumentParser.parse_args()`` method is called. The method looks for an environment variable that the
  36. completion hook shellcode sets, and if it's there, collects completions, prints them to the output stream (fd 8 by
  37. default), and exits. Otherwise, it returns to the caller immediately.
  38. .. admonition:: Side effects
  39. Argcomplete gets completions by running your program. It intercepts the execution flow at the moment
  40. ``argcomplete.autocomplete()`` is called. After sending completions, it exits using ``exit_method`` (``os._exit``
  41. by default). This means if your program has any side effects that happen before ``argcomplete`` is called, those
  42. side effects will happen every time the user presses ``<TAB>`` (although anything your program prints to stdout or
  43. stderr will be suppressed). For this reason it's best to construct the argument parser and call
  44. ``argcomplete.autocomplete()`` as early as possible in your execution flow.
  45. .. admonition:: Performance
  46. If the program takes a long time to get to the point where ``argcomplete.autocomplete()`` is called, the tab completion
  47. process will feel sluggish, and the user may lose confidence in it. So it's also important to minimize the startup time
  48. of the program up to that point (for example, by deferring initialization or importing of large modules until after
  49. parsing options).
  50. Specifying completers
  51. ---------------------
  52. You can specify custom completion functions for your options and arguments. Two styles are supported: callable and
  53. readline-style. Callable completers are simpler. They are called with the following keyword arguments:
  54. * ``prefix``: The prefix text of the last word before the cursor on the command line.
  55. For dynamic completers, this can be used to reduce the work required to generate possible completions.
  56. * ``action``: The ``argparse.Action`` instance that this completer was called for.
  57. * ``parser``: The ``argparse.ArgumentParser`` instance that the action was taken by.
  58. * ``parsed_args``: The result of argument parsing so far (the ``argparse.Namespace`` args object normally returned by
  59. ``ArgumentParser.parse_args()``).
  60. Completers should return their completions as a list of strings. An example completer for names of environment
  61. variables might look like this:
  62. .. code-block:: python
  63. def EnvironCompleter(**kwargs):
  64. return os.environ
  65. To specify a completer for an argument or option, set the ``completer`` attribute of its associated action. An easy
  66. way to do this at definition time is:
  67. .. code-block:: python
  68. from argcomplete.completers import EnvironCompleter
  69. parser = argparse.ArgumentParser()
  70. parser.add_argument("--env-var1").completer = EnvironCompleter
  71. parser.add_argument("--env-var2").completer = EnvironCompleter
  72. argcomplete.autocomplete(parser)
  73. If you specify the ``choices`` keyword for an argparse option or argument (and don't specify a completer), it will be
  74. used for completions.
  75. A completer that is initialized with a set of all possible choices of values for its action might look like this:
  76. .. code-block:: python
  77. class ChoicesCompleter(object):
  78. def __init__(self, choices):
  79. self.choices = choices
  80. def __call__(self, **kwargs):
  81. return self.choices
  82. The following two ways to specify a static set of choices are equivalent for completion purposes:
  83. .. code-block:: python
  84. from argcomplete.completers import ChoicesCompleter
  85. parser.add_argument("--protocol", choices=('http', 'https', 'ssh', 'rsync', 'wss'))
  86. parser.add_argument("--proto").completer=ChoicesCompleter(('http', 'https', 'ssh', 'rsync', 'wss'))
  87. Note that if you use the ``choices=<completions>`` option, argparse will show
  88. all these choices in the ``--help`` output by default. To prevent this, set
  89. ``metavar`` (like ``parser.add_argument("--protocol", metavar="PROTOCOL",
  90. choices=('http', 'https', 'ssh', 'rsync', 'wss'))``).
  91. The following `script <https://raw.github.com/kislyuk/argcomplete/master/docs/examples/describe_github_user.py>`_ uses
  92. ``parsed_args`` and `Requests <http://python-requests.org/>`_ to query GitHub for publicly known members of an
  93. organization and complete their names, then prints the member description:
  94. .. code-block:: python
  95. #!/usr/bin/env python
  96. # PYTHON_ARGCOMPLETE_OK
  97. import argcomplete, argparse, requests, pprint
  98. def github_org_members(prefix, parsed_args, **kwargs):
  99. resource = "https://api.github.com/orgs/{org}/members".format(org=parsed_args.organization)
  100. return (member['login'] for member in requests.get(resource).json() if member['login'].startswith(prefix))
  101. parser = argparse.ArgumentParser()
  102. parser.add_argument("--organization", help="GitHub organization")
  103. parser.add_argument("--member", help="GitHub member").completer = github_org_members
  104. argcomplete.autocomplete(parser)
  105. args = parser.parse_args()
  106. pprint.pprint(requests.get("https://api.github.com/users/{m}".format(m=args.member)).json())
  107. `Try it <https://raw.github.com/kislyuk/argcomplete/master/docs/examples/describe_github_user.py>`_ like this::
  108. ./describe_github_user.py --organization heroku --member <TAB>
  109. If you have a useful completer to add to the `completer library
  110. <https://github.com/kislyuk/argcomplete/blob/master/argcomplete/completers.py>`_, send a pull request!
  111. Readline-style completers
  112. ~~~~~~~~~~~~~~~~~~~~~~~~~
  113. The readline_ module defines a completer protocol in rlcompleter_. Readline-style completers are also supported by
  114. argcomplete, so you can use the same completer object both in an interactive readline-powered shell and on the bash
  115. command line. For example, you can use the readline-style completer provided by IPython_ to get introspective
  116. completions like you would get in the IPython shell:
  117. .. _readline: http://docs.python.org/3/library/readline.html
  118. .. _rlcompleter: http://docs.python.org/3/library/rlcompleter.html#completer-objects
  119. .. _IPython: http://ipython.org/
  120. .. code-block:: python
  121. import IPython
  122. parser.add_argument("--python-name").completer = IPython.core.completer.Completer()
  123. ``argcomplete.CompletionFinder.rl_complete`` can also be used to plug in an argparse parser as a readline completer.
  124. Printing warnings in completers
  125. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  126. Normal stdout/stderr output is suspended when argcomplete runs. Sometimes, though, when the user presses ``<TAB>``, it's
  127. appropriate to print information about why completions generation failed. To do this, use ``warn``:
  128. .. code-block:: python
  129. from argcomplete import warn
  130. def AwesomeWebServiceCompleter(prefix, **kwargs):
  131. if login_failed:
  132. warn("Please log in to Awesome Web Service to use autocompletion")
  133. return completions
  134. Using a custom completion validator
  135. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  136. By default, argcomplete validates your completions by checking if they start with the prefix given to the completer. You
  137. can override this validation check by supplying the ``validator`` keyword to ``argcomplete.autocomplete()``:
  138. .. code-block:: python
  139. def my_validator(current_input, keyword_to_check_against):
  140. # Pass through ALL options even if they don't all start with 'current_input'
  141. return True
  142. argcomplete.autocomplete(parser, validator=my_validator)
  143. Global completion
  144. -----------------
  145. In global completion mode, you don't have to register each argcomplete-capable executable separately. Instead, bash
  146. will look for the string **PYTHON_ARGCOMPLETE_OK** in the first 1024 bytes of any executable that it's running
  147. completion for, and if it's found, follow the rest of the argcomplete protocol as described above.
  148. Additionally, completion is activated for scripts run as ``python <script>`` and ``python -m <module>``.
  149. This also works for alternate Python versions (e.g. ``python3`` and ``pypy``), as long as that version of Python has
  150. argcomplete installed.
  151. .. admonition:: Bash version compatibility
  152. Global completion requires bash support for ``complete -D``, which was introduced in bash 4.2. On OS X or older Linux
  153. systems, you will need to update bash to use this feature. Check the version of the running copy of bash with
  154. ``echo $BASH_VERSION``. On OS X, install bash via `Homebrew <http://brew.sh/>`_ (``brew install bash``), add
  155. ``/usr/local/bin/bash`` to ``/etc/shells``, and run ``chsh`` to change your shell.
  156. Global completion is not currently compatible with zsh.
  157. .. note:: If you use setuptools/distribute ``scripts`` or ``entry_points`` directives to package your module,
  158. argcomplete will follow the wrapper scripts to their destination and look for ``PYTHON_ARGCOMPLETE_OK`` in the
  159. destination code.
  160. If you choose not to use global completion, or ship a bash completion module that depends on argcomplete, you must
  161. register your script explicitly using ``eval "$(register-python-argcomplete my-awesome-script)"``. Standard bash
  162. completion registration roules apply: namely, the script name is passed directly to ``complete``, meaning it is only tab
  163. completed when invoked exactly as it was registered. In the above example, ``my-awesome-script`` must be on the path,
  164. and the user must be attempting to complete it by that name. The above line alone would **not** allow you to complete
  165. ``./my-awesome-script``, or ``/path/to/my-awesome-script``.
  166. Activating global completion
  167. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  168. The script ``activate-global-python-argcomplete`` will try to install the file
  169. ``bash_completion.d/python-argcomplete`` (`see on GitHub`_) into an appropriate location on your system
  170. (``/etc/bash_completion.d/`` or ``~/.bash_completion.d/``). If it
  171. fails, but you know the correct location of your bash completion scripts directory, you can specify it with ``--dest``::
  172. activate-global-python-argcomplete --dest=/path/to/bash_completion.d
  173. Otherwise, you can redirect its shellcode output into a file::
  174. activate-global-python-argcomplete --dest=- > file
  175. The file's contents should then be sourced in e.g. ``~/.bashrc``.
  176. .. _`see on GitHub`: https://github.com/kislyuk/argcomplete/blob/master/argcomplete/bash_completion.d/python-argcomplete
  177. Zsh Support
  178. ------------
  179. To activate completions for zsh you need to have ``bashcompinit`` enabled in zsh::
  180. autoload -U bashcompinit
  181. bashcompinit
  182. Afterwards you can enable completion for your scripts with ``register-python-argcomplete``::
  183. eval "$(register-python-argcomplete my-awesome-script)"
  184. Tcsh Support
  185. ------------
  186. To activate completions for tcsh use::
  187. eval `register-python-argcomplete --shell tcsh my-awesome-script`
  188. The ``python-argcomplete-tcsh`` script provides completions for tcsh.
  189. The following is an example of the tcsh completion syntax for
  190. ``my-awesome-script`` emitted by ``register-python-argcomplete``::
  191. complete my-awesome-script 'p@*@`python-argcomplete-tcsh my-awesome-script`@'
  192. Fish Support
  193. ------------
  194. To activate completions for fish use::
  195. register-python-argcomplete --shell fish my-awesome-script | source
  196. or create new completion file, e.g::
  197. register-python-argcomplete --shell fish my-awesome-script > ~/.config/fish/completions/my-awesome-script.fish
  198. Completion Description For Fish
  199. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  200. By default help string is added as completion description.
  201. .. image:: docs/fish_help_string.png
  202. You can disable this feature by removing ``_ARGCOMPLETE_DFS`` variable, e.g::
  203. register-python-argcomplete --shell fish my-awesome-script | grep -v _ARGCOMPLETE_DFS | .
  204. Git Bash Support
  205. ----------------
  206. Due to limitations of file descriptor inheritance on Windows,
  207. Git Bash not supported out of the box. You can opt in to using
  208. temporary files instead of file descriptors for for IPC
  209. by setting the environment variable ``ARGCOMPLETE_USE_TEMPFILES``,
  210. e.g. by adding ``export ARGCOMPLETE_USE_TEMPFILES=1`` to ``~/.bashrc``.
  211. For full support, consider using Bash with the
  212. Windows Subsystem for Linux (WSL).
  213. External argcomplete script
  214. ---------------------------
  215. To register an argcomplete script for an arbitrary name, the ``--external-argcomplete-script`` argument of the ``register-python-argcomplete`` script can be used::
  216. eval "$(register-python-argcomplete --external-argcomplete-script /path/to/script arbitrary-name)"
  217. This allows, for example, to use the auto completion functionality of argcomplete for an application not written in Python.
  218. The command line interface of this program must be additionally implemented in a Python script with argparse and argcomplete and whenever the application is called the registered external argcomplete script is used for auto completion.
  219. This option can also be used in combination with the other supported shells.
  220. Python Support
  221. --------------
  222. Argcomplete requires Python 2.7 or 3.5+.
  223. Common Problems
  224. ---------------
  225. If global completion is not completing your script, bash may have registered a
  226. default completion function::
  227. $ complete | grep my-awesome-script
  228. complete -F _minimal my-awesome-script
  229. You can fix this by restarting your shell, or by running
  230. ``complete -r my-awesome-script``.
  231. Debugging
  232. ---------
  233. Set the ``_ARC_DEBUG`` variable in your shell to enable verbose debug output every time argcomplete runs. This will
  234. disrupt the command line composition state of your terminal, but make it possible to see the internal state of the
  235. completer if it encounters problems.
  236. Acknowledgments
  237. ---------------
  238. Inspired and informed by the optcomplete_ module by Martin Blais.
  239. .. _optcomplete: http://pypi.python.org/pypi/optcomplete
  240. Links
  241. -----
  242. * `Project home page (GitHub) <https://github.com/kislyuk/argcomplete>`_
  243. * `Documentation <https://kislyuk.github.io/argcomplete/>`_
  244. * `Package distribution (PyPI) <https://pypi.python.org/pypi/argcomplete>`_
  245. * `Change log <https://github.com/kislyuk/argcomplete/blob/master/Changes.rst>`_
  246. * `xontrib-argcomplete <https://github.com/anki-code/xontrib-argcomplete>`_ - support argcomplete in `xonsh <https://github.com/xonsh/xonsh>`_ shell
  247. Bugs
  248. ~~~~
  249. Please report bugs, issues, feature requests, etc. on `GitHub <https://github.com/kislyuk/argcomplete/issues>`_.
  250. License
  251. -------
  252. Licensed under the terms of the `Apache License, Version 2.0 <http://www.apache.org/licenses/LICENSE-2.0>`_.
  253. .. image:: https://github.com/kislyuk/argcomplete/workflows/Python%20package/badge.svg
  254. :target: https://github.com/kislyuk/argcomplete/actions
  255. .. image:: https://codecov.io/github/kislyuk/argcomplete/coverage.svg?branch=master
  256. :target: https://codecov.io/github/kislyuk/argcomplete?branch=master
  257. .. image:: https://img.shields.io/pypi/v/argcomplete.svg
  258. :target: https://pypi.python.org/pypi/argcomplete
  259. .. image:: https://img.shields.io/pypi/l/argcomplete.svg
  260. :target: https://pypi.python.org/pypi/argcomplete