6

我正在 python 中实现一个小型命令行工具,需要向用户询问几个问题。我用

raw_input('Are you male or female?')

每时每刻。现在我希望能够处理愚蠢的用户(或者那些懒得阅读/记住文档的用户),所以我需要检查答案是否有意义。

gender = ''
while gender not in ['male', 'female']:
    gender = raw_input('Are you male or female?')

我想知道是否存在像 argparse 这样的东西可以自动解决这个问题,比如

import inputparse 
gender = inputparse.get_input(prompt='Are you male or female?', type=str, possible_input=['male', 'female'])

并会照顾自动检查等?

4

5 回答 5

3

这个问题很老了,但我今天正在研究它。Al Swigert 在Automate the Boring Stuff With Python中推荐了库pyinputplus

于 2020-06-24T11:18:48.127 回答
3

这个问题的公认答案:cmd您可能对图书馆感兴趣。

“Cmd 类为编写面向行的命令解释器提供了一个简单的框架。”

这个 Python Module of the Week 页面以它为特色,并提供了一些示例和解释。

于 2015-10-20T20:18:35.577 回答
1

我在这个线程中偶然发现了一个类似的库,但我对没有一个库感到非常失望,所以我写了一个。在接下来的几天里,我会在这方面做很多工作,因为我需要更多的功能来写我正在写的东西。

选一个

于 2013-10-24T17:06:44.420 回答
1

我不知道这样的库是否存在,但你可以写一个像这样的高阶函数:

def check_input(predicate, msg, error_string="Illegal Input"):
    while True:
        result = input(msg).strip()
        if predicate(result):
            return result
        print(error_string)

result = check_input(lambda x: x in ['male', 'female'],
                                   'Are you male or female? ')
print(result)

输出:

你是男性还是女性?富
非法输入
你是男性还是女性?酒吧
非法输入
你是男性还是女性?男性
非法输入
你是男性还是女性?男性
男性
于 2013-06-02T16:20:40.913 回答
1

又死灵了……

如果您需要一个简单的帮助库来解决问题,请查看click 。它的主要重点是命令行选项,但我认为它非常适合您的用例。

3 年后编辑:我现在正在使用提示工具包

于 2017-10-18T08:44:03.257 回答