python library for user input

前端 未结 5 1666
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-05 17:37

I am implementing a small command line tool in python that needs to ask the user a couple of questions. I use

raw_input(\'Are you male or female?\')
<         


        
相关标签:
5条回答
  • 2021-01-05 18:10

    Necromanting again...

    Please have a look at click if you need a simple helper library for questions. Its main focus are command line options, but it’s a good fit for your use case, I think.

    0 讨论(0)
  • 2021-01-05 18:16

    From the accepted answer to this question: the cmd library might be of interest to you.

    "The Cmd class provides a simple framework for writing line-oriented command interpreters."

    This Python Module of the Week page features it, and it has some examples and explanations.

    0 讨论(0)
  • 2021-01-05 18:20

    I stumbled in this thread looking for a similar library and i was quite disappointed for the fact that there isn't one, so i wrote one. I will work a lot on this in the next days because i need a lot more features for what i'm writing.

    pickone

    0 讨论(0)
  • 2021-01-05 18:21

    I don't know if such a library exists, but you could write an high-order function like this:

    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)
    

    Output:

    Are you male or female? foo
    Illegal Input
    Are you male or female? bar
    Illegal Input
    Are you male or female? Male
    Illegal Input
    Are you male or female? male
    male
    
    0 讨论(0)
  • 2021-01-05 18:22

    This question is quite old, but I'm researching it today. The library pyinputplus is recommended by Al Swigert in Automate the Boring Stuff With Python

    0 讨论(0)
提交回复
热议问题