4

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.

Dhruv Pillai
  • 112
  • 4

1 Answers1

3

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.

mincrmatt12
  • 382
  • 3
  • 12