Search code examples
pythonlinuxunixcommand-lineautocomplete

How to make a python, command-line program autocomplete arbitrary things NOT interpreter


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.


Solution

  • Use Python's readline bindings. For example,

    import readline
    
    def completer(text, state):
        options = [i for i in commands if i.startswith(text)]
        if state < len(options):
            return options[state]
        else:
            return None
    
    readline.parse_and_bind("tab: complete")
    readline.set_completer(completer)
    

    The official module docs aren't much more detailed, see the readline docs for more info.