Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to supply multiple options with array validation?

Given I have code like this:

columns = ['col1', 'col2', 'col3', 'col4']

@click.option('--columns', is_flag=False, 
  default=columns, show_default=True, metavar='<columns>', type=click.Choice(columns), 
  help='Sets target columns', multiple=True)

Then I can call my app like this:

./myapp --columns=col1

However, how to make this work with multiple items separated by comma, like so:

./myapp --columns=col1,col3

My goal is to retrieve the passed values from an resulting columns array ['col1', 'col3'].

I do NOT want to pass the option multiple times.

like image 625
Sebastian Roth Avatar asked Dec 15 '22 10:12

Sebastian Roth


1 Answers

The multiple keyword in click.option is so you can pass the same option multiple times, e.g. --columns=col1 --columns=col2. Instead you can accept a string for columns and then extract and validate the columns yourself:

cols = ['col1', 'col2', 'col3', 'col4']

@click.option('--columns', is_flag=False, default=','.join(cols), show_default=True,
              metavar='<columns>', type=click.STRING, help='Sets target columns')
@click.command()
def main(columns):
    # split columns by ',' and remove whitespace
    columns = [c.strip() for c in columns.split(',')]

    # validate passed columns
    for c in columns:
        if c not in cols:
            raise click.BadOptionUsage("%s is not an available column." % c)

    print(columns)
like image 148
Rahiel Kasim Avatar answered Dec 30 '22 11:12

Rahiel Kasim