Search code examples
pythonpython-click

Creating hierarchical commands using Python Click


Suppose I want to create a CLI that looks like this

cliName user create
cliName user update

How would I do this?

I've tried doing something like this -

@click.group()
def user():
   print("USER")
   pass

@user.command()
def create():
    click.echo("create user called")

when I run cliName user create, the print statements do not run. Nothing runs.


Solution

  • #!/usr/bin/env python
    
    import click
    
    
    @click.group()
    def cli(**kwargs):
        print(1)
    
    
    @cli.group()
    @click.option("--something")
    @click.option("--else")
    def what(**kwargs):
        print(2)
    
    
    @what.command()
    @click.option("--chaa")
    def ever(**kwargs):
        print(3)
    
    
    if __name__ == '__main__':
        cli()
    
    
    # ./cli.py what ever
    # 1
    # 2
    # 3