celigo/celigo/prompt.py

42 lines
1.3 KiB
Python

import collections
def _get_input():
""" Putting in a method so we can mock it easier"""
return raw_input("(Type a number) (Ctrl+c to cancel): ").rstrip("\n")
def prompt(message, options=None, retries=3):
"""
Accept a list of options (or defaults to Yes/No) and continue asking
until one of the appropriate answers are accepted, or failing after
3 times.
:params message: The message to show as a prompt
:params options: An iterator of strings to show as each question in the
prompt
:return selected: Return the selected answer from options.
"""
if options is None:
options = ("Yes", "No")
mapping = collections.OrderedDict()
for idx, v in enumerate(options):
mapping[str(idx + 1)] = v
option_strings = "\n".join(" {0} - {1}".format(k, v)
for k, v in mapping.items())
print(message)
print(option_strings)
option = None
while True:
try:
index = _get_input()
option = mapping[index]
except KeyError:
print("Invalid Option, try again (Ctrl+C to cancel)")
retries -= 1
if retries:
continue
else:
break
break
return option