正文
nargs: 指定命令行参数接收的值的个数
下面,我们再看看相关的例子。
指定 type
我们可以使用 type 来指定参数类型:
import click
@click.command()
@click.option('--rate', type=float, help='rate') # 指定 rate 是 float 类型
def show(rate):
click.echo('rate: %s' % rate)
if __name__ == '__main__':
show()
执行情况:
$ python click_type.py --rate 1
rate: 1.0
$ python click_type.py --rate 0.66
rate: 0.66
可选值
在某些情况下,一个参数的值只能是某些可选的值,如果用户输入了其他值,我们应该提示用户输入正确的值。在这种情况下,我们可以通过 click.Choice() 来限定:
import click
@click.command()
@click.option('--gender', type=click.Choice(['man', 'woman'])) # 限定值
def choose(gender):
click.echo('gender: %s' % gender)
if __name__ == '__main__':
choose()
执行情况:
$ python click_choice.py --gender boy
Usage: click_choice.py [OPTIONS]
Error: Invalid value for "--gender": invalid choice: boy. (choose from man, woman)
$ python click_choice.py --gender man
gender: man
多值参数
有时,一个参数需要接收多个值。option 支持设置固定长度的参数值,通过 nargs 指定。
看看例子就明白了:
import click
@click.command()
@click.option('--center', nargs=2, type=float, help='center of the circle')
@click.option('--radius', type=float, help='radius of the circle')
def circle(center, radius):
click.echo('center: %s, radius: %s' % (center, radius))
if __name__ == '__main__':
circle()
在上面的例子中,option 指定了两个参数:center 和 radius,其中,center 表示二维平面上一个圆的圆心坐标,接收两个值,以元组的形式将值传递给函数,而 radius 表示圆的半径。
执行情况:
$ python click_multi_values.py --center 3