Create multiple sub commands with [Click]
Description
I'd like to create the script that includes some options such as the awscli
.
We can create it easy to use the Click
library.
So, I write a sample code about creating sub-command with Click
.
Premise
Python : >= 3.7
Click : >= 7.0
Code
import click
def main():
cmd()
@click.group()
def cmd():
"""First layer sub-command group
"""
pass
@cmd.group()
def sub_command_1():
"""Second layer sub-command group
"""
pass
@cmd.group()
def sub_command_2():
"""Second layer sub-command group
"""
pass
@sub_command_1.command()
def sub_command_1_1():
print("Hello, subcommand 1 under the 1st layer subcommand 1")
@sub_command_1.command()
def sub_command_1_2():
print("Hello, subcommand 2 under the 1st layer subcommand 1")
@sub_command_1.command()
def sub_command_1_3():
print("Hello, subcommand 3 under the 1st layer subcommand 1")
@sub_command_2.command()
def sub_command_2_1():
print("Hello, subcommand 1 under the 1st layer subcommand 2")
@sub_command_2.command()
def sub_command_2_2():
print("Hello, subcommand 2 under the 1st layer subcommand 2")
if __name__ == "__main__":
main()
Sample of executing result
- Execute with no argument
(env) ~>python sample.py
Usage: sample.py [OPTIONS] COMMAND [ARGS]...
First layer sub-command group
Options:
--help Show this message and exit.
Commands:
sub-command-1 Second layer sub-command group
sub-command-2 Second layer sub-command group
- Execute with 1st argument
(env) ~>python sample.py sub-command-2
Usage: sample.py sub-command-2 [OPTIONS] COMMAND [ARGS]...
Second layer sub-command group
Options:
--help Show this message and exit.
Commands:
sub-command-2-1
sub-command-2-2
- Execute with until 2nd argument
(env) ~>python sample.py sub-command-2 sub-command-2-1
Hello, subcommand 1 under the 1st layer subcommand 2