Skip to content

Instantly share code, notes, and snippets.

@nitori
Created March 29, 2024 08:52
Show Gist options
  • Save nitori/d259d09093ef9d7287d215f3d5ab9b96 to your computer and use it in GitHub Desktop.
Save nitori/d259d09093ef9d7287d215f3d5ab9b96 to your computer and use it in GitHub Desktop.
Simple linux cli style user choice function
def choose(text, options="Yn"):
"""
text: prompt to the user.
options: set of characters. one upper case may be
used to indicate a default value.
Examples:
answer = choose("Continue?")
# outputs: "Continue? (Y/n): "
answer = choose("The next operation will be destructive! Continue?", "yN")
if answer == 'n':
sys.exit(0)
"""
default = ''.join(char for char in options if char.isupper())
default = default.strip().lower()
if len(default) > 1:
raise ValueError('Must not have more than 1 default option')
others = ''.join(char for char in options if char.islower())
others = others.strip().lower()
while True:
opts = '/'.join(options)
result = input(f'{text} ({opts}): ')
result = result.strip().lower()
if not result and default:
return default
if result and result in others:
return result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment