简体   繁体   中英

Is there a Python library for handling and validating user input?

I have a project that involves asking for (for now, command-line) feedback from the user every so often while its main method runs.

So far I have been using input('{my_prompt}') to obtain this input from my user, but I have to quite annoyingly handle user input every time I invoke input() . This makes my code balloon to > 5 lines of code per user input line, which feels quite excessive. Some of my user input handling includes the below.

if input.lower() not in ['y', 'n']:
    raise ValueError('Not valid input! Please enter either "y" or "n"')
if input.lower() == 'y':
    input = True
else:
    input = False

The above could be handled in 1 line of code if the user were passing command line arguments in and I could use argparse , but unfortunately the sheer volume of prompts prevents command line arguments from being a viable option.

I am familiar with the libraries cmd and click , but as far as I can tell, they both lack the functionality that I would like from argparse , which is namely to validate the user input.

In summary, I'm looking for a user input library that validates input and can return bool values without me having to implement the conversion every time.

If all you need is to check "yes/no" prompts, click supports it natively with click.confirm :

if click.confirm("Do you want to do this thing?"):
    # ... do something here ....

There are a variety of other input-handling functions part of click , which are documented in the User Input Prompts section of the documentation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM