通过带有 Foo() 参数的 运行 子命令在主点击组命令上实例化 Foo() class

Instantiate Foo() class on main click group command by running subcomand with Foo() arguments

我想 运行 带有可变参数的 click 子命令将用于在 main() 组命令上实例化 class Foo(*args) 以创建实例由其子命令使用的 Foo() 的数量,以便它与点击的方式一致:

$ python foo.py subcommand arg1 arg2 ... argN

这个问题是基于我的 和@StephenRauch 的回答。

import click

class Foo(object):
    def __init__(self, *args):
        self.args = args

    def log(self):
        print('self.args:', self.args)

pass_foo = click.make_pass_decorator(Foo)

@click.group()
@click.pass_context
def main(ctx):
    magic_to_get_myargs()

    ctx.obj = Foo(myargs)
    print("main:\n", "ctx.obj.args:", ctx.obj.args)

@main.command()
@click.argument('myargs', nargs=-1)
@pass_foo
def run(foo, myargs):
    magic_to_send_myargs()

    print("run:\n", 'foo.args:', foo.args)
    foo.log()

main()

我希望通过 运行ning 一个子命令在主组命令上初始化 Foo class 并取回它的对象以在子命令中使用它。

基于@StephenRauch 的 我自己找到了解决方案。

代码

import click

class MyGroup(click.Group):
    def invoke(self, ctx):
        ctx.obj = tuple(ctx.args)
        super(MyGroup, self).invoke(ctx)

class Foo(object):
    def __init__(self, *args):
        self.args = args

    def log(self):
        print('self.args:', self.args)

pass_foo = click.make_pass_decorator(Foo)

@click.group(cls=MyGroup)
@click.pass_context
def main(ctx):
    ctx.obj = Foo(*ctx.obj)
    print("main:\n", "ctx.obj.args:", ctx.obj.args)

@main.command()
@pass_foo
@click.argument('myargs', nargs=-1)
def run(foo, myargs):
    print("run:\n", 'foo.args:', foo.args)
    foo.log()

if __name__ == "__main__":
    commands = (
        'run arg1 arg2 arg3',
        'run --help',
        '--help',
    )

    import sys, time

    time.sleep(1)
    print('Click Version: {}'.format(click.__version__))
    print('Python Version: {}'.format(sys.version))
    for cmd in commands:
        try:
            time.sleep(0.1)
            print("\n", '-' * 50)
            print('> ' + cmd)
            time.sleep(0.1)
            main(cmd.split())

        except BaseException as exc:
            if str(exc) != '0' and \
                    not isinstance(exc, (click.ClickException, SystemExit)):
                raise

结果

Click Version: 7.0
Python Version: 3.7.2 (default, Dec 29 2018, 06:19:36) 
[GCC 7.3.0]

 --------------------------------------------------
> run arg1 arg2 arg3
main:
 ctx.obj.args: ('arg1', 'arg2', 'arg3')
run:
 foo.args: ('arg1', 'arg2', 'arg3')
self.args: ('arg1', 'arg2', 'arg3')

 --------------------------------------------------
> run --help
main:
 ctx.obj.args: ('--help',)
Usage: test3.py run [OPTIONS] [MYARGS]...

Options:
  --help  Show this message and exit.

 --------------------------------------------------
> --help
Usage: test3.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  run