DEV Community

Kelvin Wangonya
Kelvin Wangonya

Posted on • Originally published at wangonya.com

6

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.

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay