DEV Community

Kelvin Wangonya
Kelvin Wangonya

Posted on • Originally published at wangonya.com

Adding arguments to CLI commands

Arguments work very similarly to options. If you're familiar with functional programming, then you're familiar with arguments. The concept is the same in Click.

Let's edit our code a bit to see how we can integrate arguments.

# helloworld.py

import click

@click.command()
@click.option('-c', '--case', type=click.Choice(['upper', 'lower']))
@click.argument('person', default='you')
def hello(case, person):
    response = "Hello World! Also, hey {} ☺️".format(person)
    if case == 'upper':
        click.echo(response.upper())
    elif case == 'lower':
        click.echo(response.lower())
    else:
        click.echo(response)
Enter fullscreen mode Exit fullscreen mode

Just like with commands and options, Click provides a decorator to add arguments.

@click.argument('person', default='you')
Enter fullscreen mode Exit fullscreen mode

We specify that hello() should expect an argument person to be passed in when it's called, and add a default value so that it's ok to call the command without passing in the argument.

Saving and running the app gives the following results:

(venv) $ hello  # no argument - default will be used
Hello World! Also, hey you ☺️

(venv) $ hello Meg  # Meg is the argument
Hello World! Also, hey Meg ☺️

(venv) $ hello chris -c upper   # combining arguments with options
HELLO WORLD! ALSO, HEY CHRIS ☺️
Enter fullscreen mode Exit fullscreen mode

With options and arguments, you can add a lot of functionality to a single command.

Top comments (0)