Arbitrary command line keywords with Python's

2019-07-26 20:37发布

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条回答
戒情不戒烟
2楼-- · 2019-07-26 20:57

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

查看更多
登录 后发表回答