【问题标题】:python library for user input用于用户输入的python库
【发布时间】:2013-06-02 16:14:51
【问题描述】:

我正在 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'])

并会负责自动检查等?

【问题讨论】:

  • 鉴于您所展示的内容,编写自己的内容很容易。您的问题是是否有标准或通用库可以做到这一点?
  • 你说得对,这很简单,但就像 argparse 比我自己实现的要多得多(自动生成 --help 等),我原以为有类似的东西这个问题

标签: python user-input


【解决方案1】:

从接受的答案到this question:您可能对cmd 库感兴趣。

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

This Python Module of the Week page 有特色,并且有一些例子和解释。

【讨论】:

    【解决方案2】:

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

    中推荐的

    【讨论】:

      【解决方案3】:

      死灵再次...

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

      3 年后编辑:我现在使用 prompt toolkit

      【讨论】:

        【解决方案4】:

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

        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)
        

        输出:

        你是男性还是女性?富 非法输入 你是男性还是女性?酒吧 非法输入 你是男性还是女性?男性 非法输入 你是男性还是女性?男性 男性

        【讨论】:

          【解决方案5】:

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

          pickone

          【讨论】:

            猜你喜欢
            • 2019-04-29
            • 1970-01-01
            • 2012-11-26
            • 1970-01-01
            • 2020-09-21
            • 2021-08-29
            • 1970-01-01
            • 2014-06-17
            • 2020-08-16
            相关资源
            最近更新 更多