Using the CLI library click
I have an application script app.py
with the two sub commands read
and write
:
@click.group()
@click.pass_context
def cli(ctx):
pass
@cli.command()
@click.pass_context
def read(ctx):
print("read")
@cli.command()
@click.pass_context
def write(ctx):
print("write")
I want to declare a common option --format
. I know I can add it as an option to the command group via
@click.group()
@click.option('--format', default='json')
@click.pass_context
def cli(ctx, format):
ctx.obj['format'] = format
But then I cannot give the option after the command, which in my use case is a lot more natural. I want to be able to issue in the shell:
app.py read --format XXX
But with the outlined set-up I get the message Error: no such option: --format
. The script only accepts the option before the command.
So my question is: How can I add a common option to both sub commands so that it works as if the option were given to each sub command?
cannot give the option after the subcommand
? If you put the format on cli, you execute it withread --format XXX
right? – Biotypeapp.py read --format XXX
I get the errorError: no such option: --format
. Onlyapp.py --format XXX read
works. (I will update the question to make it clearer.) – Acaleph