命令之间共享的选项和标志 [英] Shared options and flags between commands

查看:90
本文介绍了命令之间共享的选项和标志的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我的CLI实用程序有三个命令: cmd1 cmd2 cmd3

Say my CLI utility has three commands: cmd1, cmd2, cmd3

我希望 cmd3 具有与相同的选项和标志cmd1 cmd2 。就像某种继承。

And I want cmd3 to have same options and flags as cmd1 and cmd2. Like some sort of inheritance.

@click.command()
@click.options("--verbose")
def cmd1():
    pass

@click.command()
@click.options("--directory")
def cmd2():
    pass

@click.command()
@click.inherit(cmd1, cmd2) # HYPOTHETICAL
def cmd3():
    pass

因此 cmd3 将带有标志-详细和选项-目录。是否可以通过Click做到这一点?也许我只是忽略了文档中的某些内容...

So cmd3 will have flag --verbose and option --directory. Is it possible to make this with Click? Maybe I just have overlooked something in the documentation...

编辑:我知道我可以使用来做到这一点。 click.group()。但是,随后必须在组命令之前指定该组的所有选项。我想在命令后正常使用所有选项。

I know that I can do this with click.group(). But then all the group's options must be specified before group's command. I want to have all the options normally after command.

cli.py --verbose --directory / tmp cmd3 -> cli.py cmd3 --verbose --directory / tmp

推荐答案

我找到了简单的解决方案!我对 https://github.com/pallets/click/issues/108

I have found simple solution! I slightly edited the snippet from https://github.com/pallets/click/issues/108 :

import click


_cmd1_options = [
    click.option('--cmd1-opt')
]

_cmd2_options = [
    click.option('--cmd2-opt')
]


def add_options(options):
    def _add_options(func):
        for option in reversed(options):
            func = option(func)
        return func
    return _add_options


@click.group()
def group(**kwargs):
    pass


@group.command()
@add_options(_cmd1_options)
def cmd1(**kwargs):
    print(kwargs)


@group.command()
@add_options(_cmd2_options)
def cmd2(**kwargs):
    print(kwargs)


@group.command()
@add_options(_cmd1_options)
@add_options(_cmd2_options)
@click.option("--cmd3-opt")
def cmd3(**kwargs):
    print(kwargs)


if __name__ == '__main__':
    group()

这篇关于命令之间共享的选项和标志的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆