Reputation: 903
I am using python click for my development purposes. I have the following command line with one option:
add student -n xx -n yy
code :
@click.group()
@click.version_option("Development", help="Echo version and exit")
@click.help_option(help = "Use this on subcommands for more information")
def cli():
'''Add a student/teacher/principal'''
@cli.command()
@click.option('--name', '-n', required=True, help='Specify the name of the student')
def student(name):
'''Add a Student'''
While using the above command line, how I am able to use the same option multiple times?? I see that the value for name
is yy
. How can I avoid taking multiple -n
if multiple is not true??
Thank you.
Upvotes: 2
Views: 3260
Reputation:
Use the kwargs
multiple=True
Running this
import click
@click.group()
@click.version_option("Development", help="Echo version and exit")
@click.help_option(help="Use this on subcommands for more information")
def cli():
"""Add a student/teacher/principal"""
def validate_student(ctx, param, value):
try:
if len(value) > 1:
raise ValueError
else:
return value
except ValueError:
raise click.BadParameter('Students should be not more than 1')
@cli.command()
@click.option('--name', '-n', required=True, multiple=True, help='Specify the name of the student',
callback=validate_student)
def student(name):
"""Add a Student"""
print(name)
if __name__ == "__main__":
student()
Gives me this
$ python3 add.py -n xx -n yy
Usage: add.py [OPTIONS]
Error: Invalid value for "--name" / "-n": Students should be not more than 1
Process finished with exit code 0
But passing only 1 param returns:
$ python3 add.py -n xx
('xx',)
This is documented here: http://click.pocoo.org/5/options/#multi-value-options and here http://click.pocoo.org/5/options/#callbacks-for-validation
Upvotes: 1
Reputation: 3543
You can use multiple with a tweak. Make the multiple=True
. Accept the multiple values. And throw error if there are more than one item.
def check_multiple(ctx, param, value):
if len(name) > 1:
click.echo('Multiple options are not accepted!')
ctx.abort()
@cli.command()
@click.option('--name', '-n', required=True, multiple=True, callback=check_multiple, help='Specify the name of the student')
def student(name):
''' '''
Since, I don't have a current setup, the above code is not tested; Derived from the documentation.
Upvotes: 2