1

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?

4
  • What library provides click? Commented Apr 29, 2016 at 9:38
  • pip list|grep click click (6.6) Commented Apr 29, 2016 at 9:45
  • You could provide a link. Commented Apr 29, 2016 at 9:46
  • Sure, I'm using this guide: click.pocoo.org/6 Commented Apr 29, 2016 at 9:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.