Python中有没有HighLine的等价物?

7 投票
2 回答
543 浏览
提问于 2025-04-17 16:23

HighLine 是一个 Ruby 库,用来简化控制台的输入和输出。它提供了一些方法,可以让你请求用户输入并验证这些输入。有没有类似的功能可以在 Python 中使用呢?

为了展示 HighLine 的功能,来看下面这个例子:

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 来表示是或不是”,然后让用户再输入一次。如果用户直接按回车,它会默认选择 y。最后,当输入完成后,结果会保存在 input 里。这里有一个例子,用户第一次输入了“EH???”,然后输入了“y”:

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

在 Python 中有没有同样简单的方法来实现这个功能呢?

2 个回答

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()
3

你可以使用Python 3的一个模块,叫做cliask。这个模块的灵感来自于IT Ninja的一个回答,修复了其中的一些不足,并且支持通过正则表达式、条件判断、元组或列表来进行验证。

获取这个模块最简单的方法是通过pip来安装(想了解其他安装方法,可以查看这个说明文档):

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

撰写回答