'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.
Solution 1:[1]
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
