[英]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()
.到目前为止,我一直在使用
input('{my_prompt}')
从我的用户那里获取此输入,但是每次调用input()
时我都必须非常烦人地处理用户输入。 This makes my code balloon to > 5 lines of code per user input line, which feels quite excessive.这使我的代码膨胀到每个用户输入行超过 5 行代码,这感觉非常过分。 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.如果用户正在传递命令行 arguments 并且我可以使用
argparse
,则可以在 1 行代码中处理上述内容,但不幸的是,提示的数量之多阻止了命令行 arguments 成为一个可行的选项。
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.我熟悉库
cmd
和click
,但据我所知,它们都缺乏我想要的argparse
功能,即验证用户输入。
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.总之,我正在寻找一个用户输入库,它可以验证输入并可以返回
bool
值,而无需我每次都实现转换。
If all you need is to check "yes/no" prompts, click
supports it natively with click.confirm
:如果您只需要检查“是/否”提示,则
click
使用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. click
的一部分还有许多其他输入处理功能,这些功能都记录在文档的用户输入提示部分中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.