Search code examples
pythonpython-click

Click : options of first command not usable after using CommandCollection()


I want to have two separate sub-commands, each with different options.

E.g. -

command first --one --two
command second --three

The options one and two are just for sub-command first and three for sub-command second.

My code is of the form:

@click.group()
@click.option('--one')
@click.option('--two') 
def cli1():
 print("clione")
@cli1.command()
def first():
   pass

@click.group()
@click.option('--three')
def cli2():
 print("clitwo")
@cli2.command()
def second():
   pass

cli = click.CommandCollection(sources=[cli1, cli2])

if __name__ == '__main__':
     cli()  

But after running it, I'm not able to run any of the options for each sub-command.

I used this : Merging Multi Commands


Solution

  • I find the easiest way to do sub-commands is to only use one group, and I usually name that group cli like:

    @click.group()
    def cli():
        pass
    

    Using the name of the group, declare commands like:

    @cli.command()
    def name_of_command():
        ....
    

    Test Code:

    import click
    
    @click.group()
    def cli():
        pass
    
    @cli.command()
    @click.option('--one')
    @click.option('--two')
    def first(one, two):
        click.echo("clione %s %s" % (one, two))
    
    @cli.command()
    @click.option('--three')
    def second(three):
        click.echo("clitwo %s" % three)
    
    cli('first --one 4'.split())
    

    Results

    clione 4 None