Forem

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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay