Search code examples
pythonpython-click

Execute only final command in nested list of groups in python click


I'm creating a deeply nested set of commands as click.group()s. I would like to ONLY execute the last group (command) input to the cli when I press the Enter key.

For instance:

cli sub_command subsub_command # < -- should only execute subsub_command

... should ONLY execute the last command subsub_command, however, it appears that click want's to execute the full stack of commands. (oddly it excludes subsub_command?):

$ cli sub-command subsub-command 
I am the root_command
I am sub_command
Usage: cli sub-command subsub-command [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

It also appears that it is running everything EXCEPT for the last command. Why is it displaying the help for subsub_command instead of simply executing it?

Here is my click code:

import os
import sys

import click

@click.group(invoke_without_command=True)
def cli():
    print('I am the root_command')

@cli.group()
def sub_command(invoke_without_command=True):
    print('I am sub_command')

@sub_command.group()
def subsub_command(invoke_without_command=True):
    print('I am the subsub_command')

if __name__ == '__main__':
    cli()

Any thoughts are helpful. Thanks!


Solution

  • That's because you are using @cli.group over and over.

    Commands are defined with @cli.command

    So for example:

    import click
    
    
    @click.group()
    def cli():
        pass
    
    
    @cli.command(name='hello')
    def hello():
        print('hello world!')
    

    The idea of @group is to combine multiple commands together, the group method is used for defining a common context code for the entire group.