Python command line artifact Click concise notes

Keywords: Python github pip

Recently, I saw a blog post on Python command line processing in PyChina, which is rich, easy to understand and practical, so it is reproduced here.

Click

Click(https://github.com/pallets/click ) It's a third-party module written in Python to create command lines quickly. We know that Python has an Argparse built in( https://docs.python.org/2/howto/argparse.html ) Standard libraries are used to create command lines, but they are cumbersome to use. Click is like requests compared to urllib, compared to Argparse.

Rapid use

Click can be used in two steps:

Decorate a function with @click.command() to make it a command-line interface;
Use decorative functions such as @click.option() to add command-line options and so on.
One of its typical uses is as follows:

import click

@click.command()
@click.option('--param', default=default_value, help='description')
def func(param):
    pass

Next, let's take a look at the official documents.( http://click.pocoo.org/6/ ) An introductory example:

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()

In the example above, the function hello has two parameters: count and name, whose values are obtained from the command line.

  • @ click.command() makes the function hello a command line interface;
  • @ The first parameter of click.option specifies the name of the command line option. As you can see, the default value of count is 1.
  • click.echo is used for output to achieve better compatibility, because print is used differently in Python 2 and Python 3.

Look at the implementation:

$ python hello.py
Your name: Ethan           # Here'Your name:'(prompt in the corresponding code) is displayed and user input is accepted.
Hello Ethan!

$ python hello.py --help   # click helps us automatically generate `help'usage
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.

$ python hello.py --count 3 --name Ethan    # Specify the value of count and name
Hello Ethan!
Hello Ethan!
Hello Ethan!

$ python hello.py --count=3 --name=Ethan    # You can also use `=', which is equivalent to the above.
Hello Ethan!
Hello Ethan!
Hello Ethan!

$ python hello.py --name=Ethan              # No count is specified. The default value is 1.
Hello Ethan!

click.option

The most basic use of option is to read parameter values from the command line by specifying the name of the command line option, and then pass them to the function. In the example above, we see that in addition to setting the name of the command line option, we also specify default values, help instructions, etc. The commonly used setting parameters for option are as follows:

  • Default: Set default values for command line parameters
  • help: parameter description
  • Type: Parameter type, which can be string, int, float, etc.
  • Prompt: When the corresponding parameters are not entered on the command line, the prompt prompts the user to enter them.
  • nargs: Number of values received by specifying command line parameters

Next, let's look at some examples.

Specify Type

We can use type to specify parameter types:

import click

@click.command()
@click.option('--rate', type=float, help='rate')   # Specify rate as float type
def show(rate):
    click.echo('rate: %s' % rate)

if __name__ == '__main__':
    show()

Implementation:

$ python click_type.py --rate 1
rate: 1.0
$ python click_type.py --rate 0.66
rate: 0.66

Optional value

In some cases, the value of a parameter can only be some optional value. If the user enters other values, we should prompt the user to enter the correct value. In this case, we can qualify by click.Choice():

import click

@click.command()
@click.option('--gender', type=click.Choice(['man', 'woman']))    # Limit value
def choose(gender):
    click.echo('gender: %s' % gender)

if __name__ == '__main__':
    choose()

Implementation:

$ python click_choice.py --gender boy
Usage: click_choice.py [OPTIONS]

Error: Invalid value for "--gender": invalid choice: boy. (choose from man, woman)

$ python click_choice.py --gender man
gender: man

Multivalued parameter

Sometimes, a parameter needs to receive multiple values. option supports setting parameter values of fixed length, which are specified by nargs.

Looking at the examples, we can see that:

import click

@click.command()
@click.option('--center', nargs=2, type=float, help='center of the circle')
@click.option('--radius', type=float, help='radius of the circle')
def circle(center, radius):
    click.echo('center: %s, radius: %s' % (center, radius))

if __name__ == '__main__':
    circle()
//In the example above, option specifies two parameters: center and radius, where center represents the coordinates of the center of a circle on a two-dimensional plane, receives two values, passes the values to the function in tuple form, and radius represents the radius of the circle.

//Implementation:

$ python click_multi_values.py --center 3 4 --radius 10
center: (3.0, 4.0), radius: 10.0

$ python click_multi_values.py --center 3 4 5 --radius 10
Usage: click_multi_values.py [OPTIONS]

Error: Got unexpected extra argument (5)

Input password

Sometimes, when entering a password, we want to hide the display. option provides two parameters to set the password input: hide_input and confirmation_promt, where hide_input is used to hide the input and confirmation_promt is used to repeat the input.

Take an example:

import click

@click.command()
@click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True)
def input_password(password):
    click.echo('password: %s' % password)


if __name__ == '__main__':
    input_password()

Implementation:

$ python click_password.py
Password:                         # No password will be displayed
Repeat for confirmation:          # Come again
password: 666666

Because the above writing is a bit cumbersome, click also provides a quick way to use @click.password_option(), the above code can be abbreviated as:

import click

@click.command()
@click.password_option()
def input_password(password):
    click.echo('password: %s' % password)

if __name__ == '__main__':
    input_password()

Changing the execution of command-line programs

Some parameters change the execution of command-line programs, such as entering Python at the terminal to enter the python console and typing python-version to print the python version. Click provides an eager identifier to identify the parameter name. If the parameter is entered, the established command line execution process is intercepted and a callback function is jumped to execute.

Let's look at an example:

import click

def print_version(ctx, param, value):
    if not value or ctx.resilient_parsing:
        return
    click.echo('Version 1.0')
    ctx.exit()

@click.command()
@click.option('--version', is_flag=True, callback=print_version,
              expose_value=False, is_eager=True)
@click.option('--name', default='Ethan', help='name')
def hello(name):
    click.echo('Hello %s!' % name)

if __name__ == '__main__':
    hello()

Among them:

  • is_eager=True indicates that this command-line option has priority over other options;
  • Expo_value=False indicates that if the command line option is not entered, the established command line process will be executed.
  • callback specifies the function to jump when entering the command line option.

Implementation:

$ python click_eager.py
Hello Ethan!

$ python click_eager.py --version                   # Intercept the established command line execution process
Version 1.0

$ python click_eager.py --name Michael
Hello Michael!

$ python click_eager.py --version --name Ethan      # Ignore the name option
Version 1.0

In addition to using @click.option to add optional parameters, we often use @click.argument to add fixed parameters. It is similar to option, but supports fewer functions than option.

Introductory use

Here is a simple example:

import click

@click.command()
@click.argument('coordinates')
def show(coordinates):
    click.echo('coordinates: %s' % coordinates)

if __name__ == '__main__':
    show()

Look at the implementation:

$ python click_argument.py                     # Error, missing parameter coordinates
Usage: click_argument.py [OPTIONS] COORDINATES

Error: Missing argument "coordinates".

$ python click_argument.py --help              # The parameters specified by argument are not displayed in help
Usage: click_argument.py [OPTIONS] COORDINATES

Options:
  --help  Show this message and exit.

$ python click_argument.py --coordinates 10    # Error usage, which is the use of the option parameter
Error: no such option: --coordinates

$ python click_argument.py 10                  # Correct, just enter the value directly.
coordinates: 10

Multiple argument s
Let's look at several examples of argument ation:

import click

@click.command()
@click.argument('x')
@click.argument('y')
@click.argument('z')
def show(x, y, z):
    click.echo('x: %s, y: %s, z:%s' % (x, y, z))

if __name__ == '__main__':
    show()

Implementation:

$ python click_argument.py 10 20 30
x: 10, y: 20, z:30

$ python click_argument.py 10
Usage: click_argument.py [OPTIONS] X Y Z

Error: Missing argument "y".

$ python click_argument.py 10 20
Usage: click_argument.py [OPTIONS] X Y Z

Error: Missing argument "z".

$ python click_argument.py 10 20 30 40
Usage: click_argument.py [OPTIONS] X Y Z

Error: Got unexpected extra argument (40)

Indefinite parameter

Another common use of argument ation is to receive unquantified parameters. Let's look at an example.

import click

@click.command()
@click.argument('src', nargs=-1)
@click.argument('dst', nargs=1)
def move(src, dst):
    click.echo('move %s to %s' % (src, dst))

if __name__ == '__main__':
    move()

Nags=-1 indicates that parameter src receives unquantified parameter values, which are passed into the function in the form of tuple. If nargs is greater than or equal to 1, it means receiving nargs parameter values. In the example above, dst receives a parameter value.

Let's look at the implementation:

$ python click_argument.py file1 trash    # src=('file1',)  dst='trash'
move (u'file1',) to trash

$ python click_argument.py file1 file2 file3 trash   # src=('file1', 'file2', 'file3')  dst='trash'
move (u'file1', u'file2', u'file3') to trash

Color output

In the previous example, we use click.echo for output. If we cooperate with the module of colorama, we can use click.secho for color output. Before using it, we use pip to install colorama:

$ pip install colorama

Take an example:

import click

@click.command()
@click.option('--name', help='The person to greet.')
def hello(name):
    click.secho('Hello %s!' % name, fg='red', underline=True)
    click.secho('Hello %s!' % name, fg='yellow', bg='black')

if __name__ == '__main__':
    hello()

Among them:

  • fg represents the foreground color (i.e. font color). The optional values are BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, etc.
  • bg represents the background color. The optional values are BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, etc.
  • underline is an underscore, and the optional styles are dim=True, bold=True, etc.

Summary

  • Decorate a function with click.command() to make it a command line interface.
  • click.option() is used to add optional parameters to support setting parameters of fixed length.
  • click.argument() is used to add fixed parameters to support setting parameters of variable length.

Source: https://funhacks.net/2016/12/20/click/

Posted by EvanMartin on Thu, 21 Mar 2019 12:48:53 -0700