1
votes

How do I add tab completion to my Python (3) code? Let's say I have this code:

test = ("January", "February", "March"...)
print(test)
answer = input("Please select one from the list above: ")

I want the user to type: Jan[TAB] and for it to autocomplete to January. Is there any simple way of doing this? Modules and scripts allowed. Note: The list would be long, with non-dictionary words.

1

1 Answers

2
votes

If you are using linux, you can use readline, if windows, you can use pyreadline, you need to install it if not have:

try:
    import readline
except ImportError:
    import pyreadline as readline

CMD = ["January", "February", "March"]

def completer(text, state):
    options = [cmd for cmd in CMD if cmd.startswith(text)]
    if state < len(options):
        return options[state]
    else:
        return None

readline.parse_and_bind("tab: complete")
readline.set_completer(completer)

while True:
    cmd = input("Please select one from the list above: ")
    if cmd == 'exit':
        break
    print(cmd)