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

时间:2019-02-16 20:38:55

标签: python command-line-interface args variadic python-click

我想运行带有可变参数的click子命令,这些参数将用于实例化main()组命令上的Foo(* args)类,以便创建要由其子命令使用的Foo()实例使其与点击的工作方式保持一致:

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

该问题基于我的initial question和@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()

我希望通过运行子命令来初始化主组命令上的Foo类,并返回其对象以在子命令中使用它。

1 个答案:

答案 0 :(得分:0)

基于similar answer中的@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