0

I am using python click module to create a CLI. The fact is that I want to have category commands with arguments, for example:

myawesomecli env info
myawesomecli env clean
myawesomecli env ...

myawesomecli database create-table <name>
myawesomecli database insert <entry>
myawesomecli database ...

So far, I can come up with this:

import click
@click.group()
@click.version_option(version='0.1 ')
def cli():
    pass

@cli.command()
@click.argument('option')
def env(option):
    if option == 'info':
        click.echo("run env info command")
    elif option == 'clean':
        click.echo("run env clean command")     
    ...

@cli.command()
@click.argument('option')
def database(option):
    if option == 'create-table':
        click.echo("run database create-table command")
    elif option == 'clean':
        click.echo("run database clean command")        
    ...

Is there a way to have a function for each subcommand instead of using the if-else's?

JRodDynamite
  • 12,325
  • 5
  • 43
  • 63
hosselausso
  • 967
  • 1
  • 10
  • 28

1 Answers1

3
import click
@click.group()
@click.version_option(version='0.1 ')
def cli():
    pass

@cli.group()
@click.argument('option')
def env(option):
   """ Define the environment of the product """
   pass

@env.command()
def info():
    click.echo("run env info command")

@env.command():
def group():
    click.echo("run env group command")
...

I'm also struggling to understand a few things but this is one idea that i hope helps.

Yonz
  • 120
  • 6