I am aware of how to setup autocompletion of python objects in the python interpreter (on unix).
- Google shows many hits for explanations on how to do this.
- Unfortunately, there are so many references to that it is difficult to find what I need to do, which is slightly different.
I need to know how to enable, tab/auto completion of arbitrary items in a command-line program written in python.
My specific use case is a command-line python program that needs to send emails. I want to be able to autocomplete email addresses (I have the addresses on disk) when the user types part of it (and optionally presses the TAB key).
I do not need it to work on windows or mac, just linux.
Follow the cmd documentation and you'll be fine
Output for tab -> tab -> send -> tab -> tab -> f -> tab
I am surprised that nobody has mentioned argcomplete, here is an example from the docs:
The posted answers work fine but I have open sourced an autocomplete library that I wrote at work. We have been using it for a while in production and it is fast, stable and easy to use. It even has a demo mode so you can quickly test what you would get as you type words.
To install it, simply run:
pip install fast-autocomplete
Here is an example:
Checkout: https://github.com/wearefair/fast-autocomplete for the source code.
And here is an explanation of how it works: http://zepworks.com/posts/you-autocomplete-me/
It deals with mis-spellings and optionally sorting by the weight of the word. (let's say
burrito
is more important thanbook
, then you giveburrito
a higher "count" and it will show up first beforebook
in the results.Words is a dictionary and each word can have a context. For example the "count", how to display the word, some other context around the word etc. In this example words didn't have any context.
Since you say "NOT interpreter" in your question, I guess you don't want answers involving python readline and suchlike. (edit: in hindsight, that's obviously not the case. Ho hum. I think this info is interesting anyway, so I'll leave it here.)
I think you might be after this.
It's about adding shell-level completion to arbitrary commands, extending bash's own tab-completion.
In a nutshell, you'll create a file containing a shell-function that will generate possible completions, save it into
/etc/bash_completion.d/
and register it with the commandcomplete
. Here's a snippet from the linked page:In this case, the typing
foo --[TAB]
will give you the values in the variableopts
, i.e.--help
,--verbose
and--version
. For your purposes, you'll essentially want to customise the values that are put intoopts
.Do have a look at the example on the linked page, it's all pretty straightforward.
Use Python's
readline
bindings. For example,The official module docs aren't much more detailed, see the readline docs for more info.