带有Python点击库的任意命令行关键字 [英] Arbitrary command line keywords with Python's click library
本文介绍了带有Python点击库的任意命令行关键字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个使用Python的 click 库构建的命令行工具.我想将此工具扩展为使用用户定义的关键字,如下所示:
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, ...)
但是,就我而言,有一些用户定义的关键字.我不知道用户要提前分隔foo或bar或其他内容.
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.
目前,我最好的解决方案是使用字符串并进行自己的解析
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.
推荐答案
我认为这应该有效:
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/高级/#forwarding-unknown-options
这篇关于带有Python点击库的任意命令行关键字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文