Easily implement subcommands with python click

Introduction

In Qiita's comment, when I checked the click that was introduced, I found that it was easy to implement subcommands, so I will summarize how to do it. A subcommand is a command in which the first argument of the script is a command, which is a format found in version control commands such as git and svn, and django's project management script manage.py.

Environment

click is not a standard python package, so install it with pip.

$ pip install click

Basic

The basic code looks like this:

import click

@click.group(invoke_without_command=True)
@click.pass_context
def cli(ctx):
    if ctx.invoked_subcommand is None:
        print ctx.get_help()
    else:
        print('gonna invoke %s' % ctx.invoked_subcommand)


@cli.command(help='description 1')
@click.argument('target', required=False)
def subcommand1(target):
    print "sub command 1"

@cli.command(help='description 2')
@click.argument('target', required=False)
def subcommand2(target):
    print "sub command 2"

if __name__ == '__main__': cli()

cli is the starting function for everything, and subcommand1 and subcommand2 are the implementations of the subcommands, respectively. Enter each description as a help variable in @ cli.command. The following shows the contents of the command help displayed.

Usage: sample.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  subcommand1  description 1
  subcommand2  description 2

You can see that subcommands 1 and 2 are registered in Commands.

Tips

Create shortcut

(Sub) The command name may be too long and you may want to create a shortcut command. In that case, extend the Group class and implement it.

...

class AliasedGroup(click.Group):
    def get_command(self, ctx, cmd_name):
        rv = click.Group.get_command(self, ctx, cmd_name)
        if rv is not None:
            return rv

        if cmd_name == 'shortcut':
            return click.Group.get_command(self, ctx, 'subcommand1')

        return None

@click.group(cls=AliasedGroup, invoke_without_command=True)
@click.pass_context
def cli(ctx):
...

As above, specify the AliasedGroup implemented as the cls argument of @ click.group. Then

$ python ./sample.py shortcut
gonna invoke shortcut
sub command 1

The implementation of sabcommand1 works as above.

Make a normal commands implementation a subcommand

If you want to divide into multiple files and implement subcommands, you can implement the command and add it to the group.

@click.group(invoke_without_command=True)
@click.pass_context
def handle(ctx):
    if ctx.invoked_subcommand is None:
        print ctx.get_help()
    else:
        print('gonna invoke %s' % ctx.invoked_subcommand)

@click.command()
def hoge():
    pass

handle.add_command(hoge)

from now on

As soon as I try it, I would like to introduce the implementation of concatenated commands.

Recommended Posts

Easily implement subcommands with python click
Easily beep with python
[python3] Implement debug log output function easily with logging and Click
Create a Python console application easily with Click
Easily serverless with Python with chalice
Implement subcommands with Python's argparse
Easily handle lists with python + sqlite3
Easily handle databases with Python (SQLite3)
[Python] Collect images easily with icrawler!
Easily post to twitter with Python 3
Easily implement ItemView incremental search with PySide
Easily download mp3 / mp4 with python and youtube-dl!
Easily implement login authentication function with Laravel
FizzBuzz with Python3
Scraping with Python
Statistics with python
Scraping with Python
Python with Go
Twilio with Python
Python click tips
Integrate with Python
Play with 2016-Python
AES256 with python
Tested with Python
python starts with ()
with syntax (Python)
Bingo with python
Zundokokiyoshi with python
Excel with Python
Microcomputer with Python
Cast with python
You can easily create a GUI with Python
Getting started with AWS IoT easily in Python
Serial communication with Python
Implement Enigma in python
Zip, unzip with python
Django 1.11 started with Python3.6
Primality test with Python
Python with eclipse + PyDev.
Socket communication with Python
Data analysis with python 2
Scraping with Python (preparation)
Try scraping with Python.
I want to easily implement a timeout in python
Easily daemonized with Supervisor
Learning Python with ChemTHEATER 03
Sequential search with Python
"Object-oriented" learning with python
Run Python with VBA
Handling yaml with python
Solve AtCoder 167 with python
Serial communication with python
[Python] Use JSON with Python
Learning Python with ChemTHEATER 05-1
Implement FReLU with tf.keras
Learn Python with ChemTHEATER
1.1 Getting Started with Python
Binarization with OpenCV / Python
3. 3. AI programming with Python
I tried to implement Minesweeper on terminal with python
Kernel Method with Python