qumusabel
qumusabel

Reputation: 41

Python Click: ignore missing argument error if a flag is set

I want to make a simple CLI program that would accept --edit-config option to open its config in an editor. However, I can't figure out how to make Click ignore Missing Argument error if I specify the --edit-config flag only.

import click

@click.group(invoke_without_command=True)
@click.argument("name")
@click.option("--edit-config", is_flag=True)
def cli(name, edit_config):
    # If we run it like
    # $ myprog --edit-config | Missing Argument: NAME
    if edit_config:
        click.echo("Editing config")
        ...
        exit(0)
    
    # But this is the main functionality
    # $ myprog John
    click.echo(f"Hello, {name}")

@cli.command()
def command_a():
    ...
...

The first command causes Missing Argument error. There can be workarounds, like nargs=-1 or required=False, however, it seems that this makes the help page to either go completely or the name argument to be marked as optional in the help message, which is not true in the majority of use cases.

Is there is a simple way to make Click not raise Missing Argument error if a certain option is specified?

Upvotes: 1

Views: 1357

Answers (1)

qumusabel
qumusabel

Reputation: 41

After reading the docs further I've found this section, which provides a way of implementing --edit-config or any other option that completely alters the execution flow.

def edit_config(ctx, param, value):
    if not value or ctx.resilient_parsing:
        return
    click.echo("Editing config")
    ctx.exit()

@click.group(invoke_without_command=True)
@click.argument("name")
@click.option("--edit-config", is_flag=True, callback=edit_config,
              is_eager=True, expose_value=False)
def cli(name):
    print(f"Hello, {name}!")

@cli.command()
def howareyou():
    print(f"How are you?")
 $ myapp John
Hello, John!

 $ myapp John howareyou
Hello, John!
How are you?

 $ myapp --edit-config
Editing config

 $ myapp --help
Usage: myapp [OPTIONS] NAME COMMAND [ARGS]...

Options:
  --edit-config 
  --help         Show this message and exit.

Commands:
  howareyou

Upvotes: 1

Related Questions