Reputation: 16870
I've been using argparse
for quite a while now, but I'm transitioning to using click
.
How can I tell click
that an option-like argument should be consumed, without having to pass --
on the command-line before that argument?
Example:
@cli.group()
@click.argument('script')
@click.argument('args', nargs=-1)
def run(script, args):
# ...
I want to be able to run this as:
mycli run foo.py arg1 --arg2
and have --arg2
in the args
list, instead of having to use the command-line as:
mycli run -- foo.py arg1 --arg2
Upvotes: 5
Views: 5712
Reputation: 49794
This is possible since Click 4.0. You need to tell click to ignore the unknown option, and that you want the options gathered up and passed in. Here is your example with the relevant changes made.
Code:
@click.group()
@click.option('--arg')
def cli(arg):
click.echo('cli arg: %s' % arg)
pass
@cli.command(context_settings=dict(
ignore_unknown_options=True,
help_option_names=[],
))
@click.argument('script')
@click.argument('args', nargs=-1, type=click.UNPROCESSED)
def run(script, args):
click.echo('script: %s' % script)
click.echo(args)
Test:
cli('--arg 3 run foo.py --arg 5 arg1 --arg2 --arg 4 --help'.split())
Produces:
cli arg: 3
script: foo.py
('--arg', '5', 'arg1', '--arg2', '"--arg', '4"', '--help')
(Source)
Upvotes: 6