Skip to content

Arguments and Flags

Sean Collings edited this page Jul 17, 2021 · 4 revisions

Arguments and Flags

Command Argumaents

When it comes to CLI's you need to be able to accept user input. Arc will look at the arguements that the function accepts to determine the possible arguments for the command.

Let's take our example from before, and add an option so the user can enter in a name instead of "Hello, World!"

from arc import CLI
cli = CLI()

@cli.command()
def greet(name):
    '''Command that greets someone'''
    print(f"Hello, {name}!")

cli()
$ python3 example.py greet --name Sean
Hello, Sean!

Easy as that! Arguments are specified on the command line with [OPTION_NAME]=[OPTION_VALUE]. All arguments specified in the arguments list will be passed to the function as arguement with the same name.

In the above example, the name option is required for the command execute.

$ python3 example.py greet
ERROR: No value provided for argument: name

If you add a default value to the arguement, the option becomes optional

from arc import CLI
cli = CLI()

@cli.command()
def greet(name="Joseph Joestar"):
    '''Command that greets someone'''
    print(f"Hello, {name}!")

cli()
$ python3 example.py greet
Hello, Joseph Joestar!

Type Conversion

Arc supports argument type conversion. Refer to supported data types for more information

Kebab Case

Arc also supports using kebab-case for command names, arguments, and flags. For example:

from arc import CLI
cli = CLI()

@cli.subcommand()
def hello_kebab(fist_name, reverse_name: bool):
    '''Command that prints greets someone'''
    if reverse_name:
        first_name = first_name[::-1]
    print(f"Hello, {first_name}!")

cli()

We could execute this like we would normally

$ python3 example.py hello_kebab --first_name Sean --reverse_name

Or we could replace it with kebab-case

$ python3 example.py hello-kebab --first-name Sean --reverse-name

Both are equally valid and have the same result

Short Args

Arguments can be given short, one character names via the short_args argument in the subcommand decorator. The short_args dictionary should map the argument's long name (the actual name in the function definition) to a unique, single character name.

from arc import CLI
cli = CLI()

@cli.subcommand(short_args = {"name": "n", "reverse": "r"})
def hello(name, reverse: bool):
    """Command that greets someone"""
    if reverse:
        name = name[::-1]
    print(f"Hello, {name}!")

cli()

Using their long names:

$ python3 example.py hello --name sean --reverse
Hello, naes!

Using their short variants

$ python3 example.py hello -n sean -r

Clone this wiki locally