python click set allowable values for option

Question:

I have created a Click command that will copy files from source to destination

The command accepts 3 parameters :

1 – Source of files

2 – Destination of files

3 – Transfer mode (local,ftp)

import click    

@click.group()
def cli():
    pass

@cli.command()
@click.argument('source')
@click.argument('destination')
@click.option('--mode', required = True)
def copy(source, destination, mode):

    print("copying files from " + source + " to " + destination + "using " + mode + " mode")


if __name__ == '__main__':
    cli() 

When I call the script using this : command.py copy "C:/" "D:/" --mode=network

I get the following output : copying files from C:/ to D:/using network mode

As you can see I specified network as mode, but I want only two options : local or ftp

So how can I use Click to set the allowable values of an option ?

Asked By: Amine Messaoudi

||

Answers:

You want to use click.Choice

@cli.command()
@click.argument('source')
@click.argument('destination')
@click.option('--mode', type=click.Choice(['local', 'ftp']), required = True)
def copy(source, destination, mode):
    print("copying files from " + source + " to " + destination + "using " + mode + " mode")
Answered By: pistolpete