Is there a Python equivalent for HighLine?

HighLine is a Ruby library to facilitate console input and output. It provides methods to query input and validate it. Is there anything that provides functionality similar to it in Python?

To show what HighLine sees in 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 

He asks, "Yes or no?" and allows the user to enter something. Until the user enters y or n (case insensitive), he prints "Answer y or n for yes or no" and allows the user to reenter the answer. Also, if the user presses Enter, it defaults to y. Finally, when this is done, the input is stored in input . Here is an example when the user first enters "EH ???" and then "y":

  Yes or no?  | y |  Eh ???
 Answer y or n for yes or no
 ?  y

Is there a similar easy way to do the same in Python?

+7
source share
2 answers

You can use the Python 3 cliask module . The module is inspired by the response of the IT ninja , corrects some flaws in it and allows checking through a regular expression, predicate, tuple or list.

The easiest way to get a module is to install it via pip (see readme for other installation methods):

 sudo pip install cliask 

Then you can use the module by import, as 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 what the session looks like 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
+3
source

The following should work the same for you, although it will not be exactly the same query style as in Ruby.

 class ValidInput(object): def __init__(self,prompt,default="",regex_validate="", invalid_response="",correct_response=""): self.prompt=prompt self.default=default self.regex_validate=regex_validate self.invalid_response=invalid_response self.correct_response=correct_response def ask(self): fin="" while True: v_in=raw_input(self.prompt) if re.match(v_in,self.regex_validate): fin=v_in print self.correct_response break else: print self.invalid_response if self.default=="break": break continue return fin 

And you would use it like:

 my_input=ValidInput("My prompt (Y/N): ",regex_validate="your regex matching string here", invalid_response="The response to be printed when it does not match the regex", correct_response="The response to be printed when it is matched to the regex.") my_input.ask() 
+3
source

All Articles