Call another click command from a click command

后端 未结 3 411
栀梦
栀梦 2021-01-01 09:37

I want to use some useful functions as commands. For that I am testing the click library. I defined my three original functions then decorated as click.co

3条回答
  •  -上瘾入骨i
    2021-01-01 09:52

    Due to the click decorators the functions can no longer be called just by specifying the arguments. The Context class is your friend here, specifically:

    1. Context.invoke() - invokes another command with the arguments you supply
    2. Context.forward() - fills in the arguments from the current command

    So your code for add_name_and_surname should look like:

    @click.command()
    @click.argument('content', required=False)
    @click.option('--to_stdout', default=False)
    @click.pass_context
    def add_name_and_surname(ctx, content, to_stdout=False):
        result = ctx.invoke(add_surname, content=ctx.forward(add_name))
        if to_stdout is True:
            sys.stdout.writelines(result)
        return result
    

    Reference: http://click.pocoo.org/6/advanced/#invoking-other-commands

提交回复
热议问题