2013-02-19 80 views
7

HighLine是一个用于缓解控制台输入和输出的Ruby库。它提供的方法可以让您请求输入并验证它。有没有提供类似于Python的功能的东西?是否有与HighLine相当的Python?

显示什么海莱不看下面的例子:

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 

它问:“是还是不是?”并让用户输入的东西。只要用户不输入y或n(不区分大小写),它就会输出“回答y或n是或不是”,并让用户再次输入答案。此外,如果用户按Enter键,则默认为y。最后,当它完成时,输入存储在input中。这里是用户首先输入“EH ???”的示例结果然后是“y”:

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

Python是否有类似的简单方法?

+0

实现起来并不困难。这只是一个正则表达式。请参阅['re'](http://docs.python.org/2/library/re.html)模块。 – Bakuriu 2013-02-19 17:29:05

+0

你在Python中的确切例子可以在[Sergii Boiko的github](https://github.com/cris/ruby-quiz-in-python/blob/master/src/highline.py) – 2013-02-19 18:20:42

+0

@BurhanKhalid如果它回答了您可能想要将其解释为问题的答案。 – 2013-02-19 20:01:07

回答

3

您可以使用Python 3模块cliask。该模块的启发是the answer of IT Ninja,修复了some deficiencies in it并允许通过正则表达式,谓词,元组或列表进行验证。

进入模块最简单的方法是通过pip安装它(见readme安装的其他方式):

sudo pip install cliask 

然后,您可以通过导入像在下面的例子中使用的模块:

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) 

这里是一个会话会是什么样运行例如当:

 
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 
+0

不错!我强烈建议这个对我来说,我或多或少只是提供一个基本的例子,说明你可能会如何实现这一点。 – 2013-02-20 14:11:45

3

以下应为工作类似,虽然它不会像在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 

而且你会用它想:

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() 
+0

中描述了类似的方法您似乎忘记了'import re'。是否需要继续?为什么在'if self.default ==“break”:\ break'之前得到'print self.invalid_response'?你没有使用Python 3的任何特定原因? – 2013-02-20 06:35:51

+0

为什么使用're.match'而不是're.search'(前者[只匹配字符串的第一个字符](http://docs.python.org/3/library/re.html#search -vs匹配))?你似乎也把参数放在're.match'中的顺序是错误的。另外,我不认为在一个模块能够做到的时候制定课程是不必要的。特别是当一个模块将使它的语义更简单。此外,默认机制不适用于您的实施。另外,不需要correct_response。为了解决所有这些问题,我发布了[答案](http://stackoverflow.com/a/14977144/789593)。 – 2013-02-20 10:09:05

相关问题