Everyone says nice Python command-line library: click



Author: HelloGitHub- Prodesire

HelloGitHub of "explain open source projects" series, Project address: https: //github.com/HelloGitHub-Team/Article

I. Introduction

In previous articles in this series, we were introduced argparseand docoptthe main functions and usage. They are distinctive, can be well done command-line tasks. argparseA process-oriented, it is necessary to set the parser, and then define the parameters, and then parses the command line, the last business logic. The docoptfirst parameter with a declarative syntax definition, and another program to parse the command line and implement business logic. In some people, these methods are not enough elegance.

Today to introduce the click is in a very familiar way to your Fun command line. Defined parameters and processing parameters on the command line program nature, and the logic and the processing parameters must be defined parameters associated. Can you use functions and decorators to achieve the logic associated with processing parameters define the parameters of it? And clickprecisely in this way is used.

本系列文章默认使用 Python 3 作为解释器进行讲解。
若你仍在使用 Python 2,请注意两者之间语法和库的使用差异哦~

Second, the introduction

click is a little code as possible in order to create a beautiful combination of command-line Python program package. It is highly configurable, but also out of the box.

It is designed to make the process of writing a command-line tool is fast and fun, but also to prevent the inability to achieve the desired CLI API generated frustration. It has the following three characteristics:

  • Arbitrarily nested command
  • Automatic generation of help
  • Lazy loading support sub-command run

Third, Quick Start

3.1 business logic

First, define business logic, is not to feel some incredible it?

Whether argparseor docoptbusiness logic are to be placed in the last step, but clickit is on the first step. Think small clickthis approach is more in line with people's thinking, right? Whatever the command line with the framework, our ultimate concern is to achieve business logic, others could save the province.

Our official example example, to introduce clickthe usage and philosophy. Assuming that the input is a command-line program nameand countfunction is to print the name of a specified number of times.

Then hello.py, it is easy to write the following code:

def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo('Hello %s!' % name)

Logic of this code is very simple cycle counttimes, click.echoprint name. Among them, click.echoand printsimilar effects, but more powerful, able to handle the situation Unicode and binary data.

3.2 define parameters

Clearly, we need to respect countand nameto define the parameters of the information to which they correspond.

  • countThe corresponding command line option --count, type a number, in the hope that we do not provide parameters, the default value is 1
  • nameThe corresponding command line option --name, type a string, we hope that when no arguments, give people tips

Use click, can be written as follows:

from click import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
              help='The person to greet.')
def hello(count, name):
    ...

In the above example:

  • Decorator way that defines the parameters, in turn tied to the processing logic, this is really elegant. And argparse, docoptcompared to, less binding process step
  • Use click.commandexpress helloa command processing
  • Use click.optionto define the parameter options
    • For --countit, use defaultto specify a default value. And because the default value is a number, thus suggesting that --countthe type of digital options
    • For --nameit, use promptto specify the prompt when this option is not input
    • Use helpto specify help information

Whether decorator way, or various default behavior clickis like it's introduction puts it, people write code as little as possible, so that the whole process becomes fast and fun.

3.3 sort codes

Use clickway is very simple, we will be aggregated under the code above, in order to have a clearer understanding of:

# hello.py
import click

@click.command()
@click.option('--count', default=1, help='Number of greetings.')
@click.option('--name', prompt='Your name',
              help='The person to greet.')
def hello(count, name):
    """Simple program that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo('Hello %s!' % name)

if __name__ == '__main__':
    hello()

If we specify the number and name:

$ python3 hello.py --count 2 --name Eric
Hello Eric!
Hello Eric!

If we do nothing is specified, you are prompted to enter a name, and a default output:

$ python3 hello.py
Your name: Eric
Hello Eric!

We can also --helpview the help information is automatically generated parameters:

Usage: hello.py [OPTIONS]

  Simple program that greets NAME for a total of COUNT times.

Options:
  --count INTEGER  Number of greetings.
  --name TEXT      The person to greet.
  --help           Show this message and exit.

IV Summary

clickThe idea is very simple, defining processing functions, the parameters are defined by its decorator. Decorator wonderful in the fact that the definition and binding the two steps into one step, so that the whole process becomes silky smooth.

clickIn addition to the Pythonicway to make the command line program to achieve become more elegant and easy to use, but also provides the ratio argparseand docopthave powerful features. In the following sections, we will gradually reveal its veil.


"Explain open source projects Series" - to let people interested in open source projects are no longer afraid, let sponsors open source projects are no longer alone. Follow our articles, you'll discover the fun of programming, the use of open source projects and found to be involved so simple. Welcome messages to contact us, join us, so that more people fall in love with open source, open source contribution ~

Guess you like

Origin www.cnblogs.com/xueweihan/p/11795284.html