Skip to main content
 首页 » 编程设计

python之使用点击包: Making an option be a choice of `int`

2024年10月17日8lvdongjie

我正在尝试制作 click.option在数字之间进行选择 0 , 1和 2 .我试过这个:

@click.Option('--verbosity', default=1, type=click.Choice([0, 1, 2])) 
def f(): 
    # ... 
    pass 

但我得到异常 TypeError: sequence item 0: expected str instance, int found .我猜 click只需要 click.Choice 中的字符串.有什么办法让它接受整数吗?我知道我可以在收到后手动转换为 int,但是如果有一种惯用的方式来接收 int选择,那会更好。

请您参考如下方法:

您可以使用IntRange(min=0, max=2):

class click.IntRange(min=None, max=None, clamp=False)

A parameter that works similar to click.INT but restricts the value to fit into a range. The default behavior is to fail if the value falls outside the range, but it can also be silently clamped between the two edges.

From the docs.