I am trying to accomplish something not very standard for CLI parsing with Click and it only works partially:
- main CLI has multiple sub-commands (in sample below 'show' and 'check')
- both those commands might have optional argument, but the argument is preceding them not following
- I decided to handle that argument in the group "above" it and pass the value in the context
Sample:
import click
@click.group()
@click.argument('hostname', required=False)
@click.pass_context
def cli(ctx, hostname=None):
""""""
ctx.obj = hostname
click.echo("cli: hostname={}".format(hostname))
@cli.command()
@click.pass_obj
def check(hostname):
click.echo("check: hostname={}".format(hostname))
@cli.command()
@click.pass_obj
def show(hostname):
click.echo("check: hostname={}".format(hostname))
if __name__ == '__main__':
cli()
The part WITH the hostname works:
> pipenv run python cli.py localhost check
cli: hostname=localhost
check: hostname=localhost
> pipenv run python cli.py localhost show
cli: hostname=localhost
check: hostname=localhost
But the part WITHOUT the hostname DOES NOT:
> pipenv run python cli.py show
Usage: cli.py [OPTIONS] [HOSTNAME] COMMAND [ARGS]...
Error: Missing command.
Anybody has an idea about the direction I should start looking into?
show
orcheck
). It would be better to use an option instead – Axrequired=False
without Using Custom Class – Obsolescent