This does not exactly behave as you described, but you could use the inquirer module (GitHub, installable with pip install inquirer
)
This module provides several command line interface tools that you may use. The most straightforward is the inquirer.list_input
function, that works like this :
import inquirer
team = inquirer.list_input("Choose team", choices=["Blackpool","Blackburn","Arsenal"])
Result (use up and down arrows to select entry):
You may also use the following optional parameters
carousel
: if True, loop back at the start when the down key is pressed on the last entry
default
: Select a default value different from the first entry
If your list of possible inputs is very long, you may use the inquirer.text
function as a drop-in replacement for input, with a custom autocomplete function.
def team_completer(text, state):
teams = ["Blackpool","Blackburn","Arsenal"]
candidates = [team for team in teams if team.startswith(text)]
if candidates:
return candidates[state % len(candidates)]
team = inquirer.text("Enter Team:", autocomplete=team_completer)
You can then use the TAB key to autocomplete results as you type. You may want to also define a validator function to ensure only a valid team is chosen
def validator(_, text):
if text in ["Blackpool","Blackburn","Arsenal"]:
return True
raise inquirer.errors.ValidationError("", reason=f'Team "{text}" do not exist')
team = inquirer.text("Enter Team:", autocomplete=team_completer, validate=validator)
Note that the validation message may not be displayed correctly on Windows though.