Arbitrary command line keywords with Python's click library

让人想犯罪 __ 提交于 2019-12-11 04:34:14

问题


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:


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



来源:https://stackoverflow.com/questions/40748513/arbitrary-command-line-keywords-with-pythons-click-library

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!