When creating a command line tool using a command line analysis tool in python, the modules used are roughly divided into the following three.
Since argparse is a standard library, it has the advantage that it can be used without thinking, and since click is not a standard module, it is easy to implement things that are difficult to implement in the standard library.
Since I have never used fire and this article is not intended to introduce command line analysis tools, I will omit further comparison and explanation here.
The method of creating a subcommand using click is as follows.
If you want to create a program that actually works, it will be as follows.
import click
@click.group()
def cli():
pass
@cli.command()
def initdb():
click.echo('Initialized the database')
@cli.command()
def dropdb():
click.echo('Dropped the database')
def main():
cli()
if __name__ == "__main__":
main()
$ python3 cli.py
Usage: cli.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
dropdb
initdb
$ python3 cli.py dropdb
Dropped the database
$ python3 cli.py dropdb --help
Usage: cli.py dropdb [OPTIONS]
Options:
--help Show this message and exit.
$ python3 cli.py initdb --help
Usage: cli.py initdb [OPTIONS]
Options:
--help Show this message and exit.
$ python3 cli.py initdb
Initialized the database
The above is how to make it when program command <options>
Recently, the number of kubectl etc. that receive two subcommands such as kubectl get pods <options>
is increasing.
Therefore, what should I do if I make it myself?
Even if I read the click document, it says how to make subcommands, but not how to make subsubcommands. I searched around some documents and the Web and thought that the following method was beautiful, so I made it.
.
├── modules
│ ├── sub1.py
│ └── sub2.py
└── cli.py
import click
from modules import sub1
from modules import sub2
@click.group()
def cli():
pass
def main():
cli.add_command(sub1.sub1cli)
cli.add_command(sub2.sub2cli)
cli()
if __name__ == "__main__":
main()
import click
@click.group()
def sub1cli():
pass
@sub1cli.command()
def sub1cmd1():
click.echo('sub1cmd1')
@sub1cli.command()
def sub1cmd2():
click.echo('sub1cmd2')
import click
@click.group()
def sub2cli():
pass
@sub2cli.command()
def sub2cmd1():
click.echo('sub2cmd1')
@sub2cli.command()
def sub2cmd2():
click.echo('sub2cmd2')
In this way, you can create it by adding click.group with click's add_command.
$ python3 cli.py
Usage: cli.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
sub1cli
sub2cli
$ python3 cli.py sub1cli
Usage: cli.py sub1cli [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
sub1cmd1
sub1cmd2
$ python3 cli.py sub2cli
Usage: cli.py sub2cli [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
sub2cmd1
sub2cmd2
Recommended Posts