Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating hierarchical commands using Python Click

Tags:

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.

like image 923
praks5432 Avatar asked Apr 18 '19 07:04

praks5432


People also ask

How do you use the click function in Python?

Python click option namesClick derives the name of the option from the long name, if both are used. In the example, we create an option with both short and long names. The name of the variable passed to the function is string , derived from the longer option name. We run the program using both option names.

How do you add a click in Python?

Open your Linux terminal or shell. Type “ pip install click ” (without quotes), hit Enter. If it doesn't work, try "pip3 install click" or “ python -m pip install click “. Wait for the installation to terminate successfully.

What is click Pass_context?

When a Click command callback is executed, it's passed all the non-hidden parameters as keyword arguments. Notably absent is the context. However, a callback can opt into being passed to the context object by marking itself with pass_context() .


1 Answers

#!/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
like image 198
Hatshepsut Avatar answered Oct 10 '22 20:10

Hatshepsut