Call another click command from a click command

后端 未结 3 430
栀梦
栀梦 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条回答
  •  悲&欢浪女
    2021-01-01 09:52

    I found these solutions more complicated. I wanted this function below to be called from another place in another package:

    @click.command(help='Clean up')
    @click.argument('path', nargs=1, default='def')
    @click.option('--info', '-i', is_flag=True,
                  help='some info1')
    @click.option('--total', '-t', is_flag=True,
                  help='some info2')
    def clean(path, info, total):
    #some definition, some actions
    
    #this function will help us
    def get_function(function_name):
    if function_name == 'clean':
        return clean
    

    I have another package, so, I would like click command above in this pack

    import somepackage1 #here is clean up click command
    from click.testing import CliRunner
    
    
    @check.command(context_settings=dict(
               ignore_unknown_options=True,
              ))
    @click.argument('args', nargs=-1)
    @click.pass_context
    def check(ctx, args):
        runner = CliRunner()
    
        if len(args[0]) == 0:
            logger.error('Put name of a command')
    
        if len(args) > 0:
            result = runner.invoke(somepackage1.get_function(args[0]), args[1:])
            logger.print(result.output)
        else:
            result = runner.invoke(somepackage1.get_function(args[0]))
        logger.print(result.output)
    

    So, it works.

    python somepackage2 check clean params1 --info
    

提交回复
热议问题