Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python click set allowable values for option

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 ?

like image 762
Amine Messaoudi Avatar asked Mar 08 '19 14:03

Amine Messaoudi


1 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")
like image 131
pistolpete Avatar answered Oct 31 '22 17:10

pistolpete