如何解决使用 click.prompt 提示可选的 IntRange
import click
numbers = []
while True:
num = click.prompt("Enter a number",type=click.IntRange(1,10),default=None)
if not num:
break
numbers.append(num)
print(f"List of numbers: {numbers}")
我希望看到这个:
Enter a number: 1
Enter a number: 2
Enter a number:
List of numbers: [1,2]
而是循环永远运行。如何指定我很乐意允许 None
作为输入,但获得使用 IntRange
的好处?
解决方法
参考文档 --> https://click.palletsprojects.com/en/8.0.x/api/?highlight=click%20prompt#click.prompt
default (Optional[Any]) – 没有输入时使用的默认值 发生。如果没有给出,它会提示直到它被中止。
如果用户只需按 Enter,您提到的默认值将用作输入。由于您已向它提供了 None
,因此 click
将继续提示响应,因为它没有得到响应。
None is default and not considered as input.
另外,因为你已经提供了一个range(1,10),所以你不能设置除[1-10] both included
之外的任何默认值,否则会报错。
现在,我对您的用例的理解是,您想处理 1-10 之间的所有值,如果用户只是按 Enter,您想跳出循环。
以下代码应指导您。
import click
numbers = []
while True:
num = click.prompt("Enter a number",type=click.IntRange(0,10),default=0)
if not num:
break
numbers.append(num)
print(f"List of numbers: {numbers}")
输出
Enter a number [0]: 1
Enter a number [0]: 2
Enter a number [0]: 3
Enter a number [0]:
List of numbers: [1,2,3]
,
一种方法(虽然感觉有点像黑客)是 create a custom type 使指定的类型可选:
import click
class OptionalParamType(click.ParamType):
def __init__(self,param_type: click.ParamType):
self.param_type = param_type
def convert(self,value,param,ctx):
if not value:
return
return self.param_type.convert(value,ctx)
这允许我们将任何 Falsy 指定为默认值(None
除外),并且一切如我们所愿:
In [8]: numbers = []
In [9]: while True:
...: num = click.prompt("Number (or enter to stop)",type=OptionalParamType(click.IntRange(1,10)),default="",show_default=False)
...: if not num:
...: break
...: numbers.append(num)
...:
Number (or enter to stop): 5
Number (or enter to stop): 10
Number (or enter to stop): 20
Error: 20 is not in the range 1<=x<=10.
Number (or enter to stop):
In [10]: numbers
Out[10]: [10,5]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。