HighLine is a Ruby library for easing console input and output. It provides methods that lets you request input and validate it. Is there something that provides functionality similar to it in Python?
To show what HighLine does see the following example:
require 'highline/import'
input = ask("Yes or no? ") do |q|
q.responses[:not_valid] = "Answer y or n for yes or no"
q.default = 'y'
q.validate = /\A[yn]\Z/i
end
It asks "Yes or no? " and lets the user input something. As long as the user does not input y or n (case-insensitive) it prints "Answer y or n for yes or no" and lets the user type an answer again. Also if the user press Enter it defaults to y. Finally, when it is done the input is stored in input
. Here is an example result where the user first input "EH???" and then "y":
Yes or no? |y| EH??? Answer y or n for yes or no ? y
Is there similarly simple way to do the same in Python?
You can use the Python 3 module cliask. The module is inspired by the answer of IT Ninja, fixes some deficiencies in it and allows validation via a regex, a predicate, a tuple or a list.
The easiest way to get the module is to install it via pip (see the readme for other ways of installing):
sudo pip install cliask
You can then use the module by importing like in the following example:
import cliask
yn = cliask.agree('Yes or no? ',
default='y')
animal = cliask.ask('Cow or cat? ',
validator=('cow', 'cat'),
invalid_response='You must say cow or cat')
print(yn)
print(animal)
And here is how a session might look when running the example:
Yes or no? |y| EH??? Please enter "yes" or "no" Yes or no? |y| y Cow or cat? rabbit You must say cow or cat Cow or cat? cat True cat