简体   繁体   中英

Python tab autocompletion in script

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM