python click set allowable values for option
Asked Answered
C

1

12

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 ?

Concert answered 8/3, 2019 at 14:38 Comment(0)
C
17

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")
Casi answered 8/3, 2019 at 14:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.