任意命令行使用Python的点击关键字库(Arbitrary command line keywor

2019-09-26 15:52发布

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.

Answer 1:

我想,这应该工作:

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()

测试:

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

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

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



文章来源: Arbitrary command line keywords with Python's click library