python Command Line Tool Click Quick Mastery

  • 2021-07-09 08:47:48
  • OfStack

Preface

Writers of Python often have to write some command-line tools. Although the standard library provides command-line parsing tool Argparse, it is very troublesome to write and I rarely use it. The best command-line tool to use is Click, an open source project of pallets, the team of Flask. Click can elegantly create a command-line tool with very little code, and it is dedicated to making the process of creating command-line tools fast and interesting.

A hundred smells is better than a try

Installation


pip install Click

Use

Create click_demo. py and write the simplest function


import click
@click.command()
def hello():
  click.echo('Hello World!')
if __name__ == '__main__':
  hello()

Running:


python click_demo.py
Hello World!

The decorator click. command () changes the function into a command-line tool in seconds, and the echo function acts as the print function.

Parameter

Decorator click. option () can specify parameters to command line functions


import click

@click.command()
@click.option("--count", default=1, help=" Number of prints ", type=int)
def hello(count):
  """
   This is 1 Simple example 
  """
  for i in range(count):
    click.echo('Hello World!')

if __name__ == '__main__':
  hello()
--count: count is the name of the parameter default: Default value for parameter type: Specify a type for a parameter help: Explanatory document

When executing the script, add parameters-help to view the description document.


$ python click_demo.py --help

Usage: click_demo.py [OPTIONS]

  This is 1 Simple example 

Options:
 --count INTEGER  Number of prints 
 --help    Show this message and exit.

Specify parameters:


>python click_demo.py --count 3

Hello World!
Hello World!
Hello World!

prompt

Some command-line tools require the user to enter information when running, and you can specify prompt parameters to the option decorator


import click

@click.command()
@click.option("--count", default=1, help=" Number of prints ", type=int)
@click.option("--name", prompt=" Please enter a name ", help=" Name ")
def hello(count, name):
  """
   This is 1 Simple example 
  """
  for i in range(count):
    click.echo(f'Hello {name}!')

if __name__ == '__main__':
  hello()

$ python click_demo.py

 Please enter a name : lzjun
Hello lzjun!

Group

An important feature of Click is its grouping function. When the logic of a command line tool is already very complex, in order to decouple, we need to put different logic in different commands, which can avoid bloated functions of a single command line tool. Take an example:


# db.py
import click

@click.group()
def db():
  pass

@click.command()
@click.option("--name", help=" User name ")
def add(name):
  """
   Add User 
  :param name:
  :return:
  """
  click.echo(f'add user {name}')

@click.command()
@click.option("--id", help=" User name ")
def delete(id):
  """
   Delete user 
  :param id:
  :return:
  """
  click.echo(f'delete user {id}')

db.add_command(delete)
db.add_command(add)

if __name__ == '__main__':
  db()

This is a command line tool for operating database DB, which provides other operations such as adding users and deleting users. If all business logic is written in one function, maintenance becomes extremely difficult.

The @ click. group decorator decorates the function as an Group object, through which many subcommands can be added.


python db.py --help
Usage: db.py [OPTIONS] COMMAND [ARGS]...

Options:
 --help Show this message and exit.

Commands:
 add    Add User  :param name: :return:
 delete  Delete user  :param id: :return:

From the help documentation, we see that add and delete are two subcommands. The flask command of the Flask framework is also an Group command.


import click
@click.command()
def hello():
  click.echo('Hello World!')
if __name__ == '__main__':
  hello()
0

Several predefined subcommands and custom commands are provided.


Related articles: