1

I have a command line tool built with Python's click library. I want to extend this tool to use user-defined keywords like the following:

$ my-cli --foo 10 --bar 20

Normally I would add the following code to my command

@click.option('--foo', type=int, default=0, ...)

However in my case there are a few keywords that are user defined. I won't know that the user wants to sepcify foo or bar or something else ahead of time.

One solution

Currently, my best solution is to use strings and do my own parsing

$ my-cli --resources "foo=10 bar=20"

Which would work, but is slightly less pleasant.

1

1 Answer 1

3

I think this should work:

import click


@click.command(context_settings=dict(ignore_unknown_options=True,))
@click.option('-v', '--verbose', is_flag=True, help='Enables verbose mode')
@click.argument('extra_args', nargs=-1, type=click.UNPROCESSED)
def cli(verbose, extra_args):
    """A wrapper around Python's timeit."""
    print(verbose, extra_args)


if __name__ == "__main__":
    cli()

Test:

$ python test.py --foo 12
False ('--foo', '12')

$ python test.py --foo 12 -v
True ('--foo', '12')

From: http://click.pocoo.org/5/advanced/#forwarding-unknown-options

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.