Python command line - click Library

Posted by dvwhi on Mon, 10 Jan 2022 15:53:21 +0100

I Know Click Library

In a series of articles on the command line, we mentioned that the Python standard library module argparse can be used to parse command line parameters ~ but because argparse is complex to use, add_ The argument method has many parameters. Therefore, the third-party library module click came into being, which greatly improves the ease of use of argparse.

Note: click third-party library is developed by Armin Ronacher, author of Flask. Click is better than argparse and requests is better than urllib.

Before using click, you need to install:

pip install click

Click module builds Python command line in the following two steps:

  • Use @ click Command () decorator, which makes the decorated function a command line interface;
  • Use @ click Option() and other decorators, add command line options.

Here is a simple example:

import click

@click.command()
@click.option('--count', default=1, help='Number of grettings.')
@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()

The hello function accepts two parameters, count and name, and reads the values from the command line respectively. The command option and echo of click module are used in the program. Their functions are as follows:

  • Command makes the function hello as the command line interface;
  • option add command line options;
  • click.echo is mainly considered from the perspective of compatibility: the print in Python 2 is a statement, while the print in Python 3 is a function.

Operation results:

 

Because we just specified prompt='Your name 'when adding the name parameter, when executing the command line, if -- name is not specified, Click will prompt the user to enter in interactive mode-- When defining the count parameter, we specify the default value of default=1.

In addition, like argparse, click will automatically generate good help information for us:

 

II Detailed usage of adding parameters

Decorator provided by Click library @ Click Option reads the parameter value from the command line by specifying the name of the command line option, and then passes it to the function. The common setting parameters of option are as follows:

  • Default sets the default value of command line parameters;
  • help parameter description;
  • Type specifies the parameter type, such as string int float;
  • Prompt when no corresponding parameter is specified on the command line, the user will be prompted for input according to prompt;
  • nargs specifies the number of values that the command line parameter accepts.

Example 1 argparse of the standard library can configure the number of parameters through nargs and set the data type of parameters through type. In click, you can also:

import click

@click.command()
@click.option('--pos', nargs=2, type=float)
def example(pos):
    click.echo('pos={}'.format(pos))

if __name__ == '__main__':
    example()

Operation results:

 

In the above example, the program will automatically convert the parameters to floating-point numbers and assign them to the variable pos in the form of tuples.

Example 2 for the command line parameter of enumeration type, you can specify the type as click Choice instance. The parameter of choice is a list, which lists all possible values.

import click

@click.command()
@click.option('--subject', type=click.Choice(['math','chinese','english']))
def score(subject):
    click.echo('{} score: 100'.format(subject))

if __name__ == '__main__':
    score()

Operation results:

 

Example 3: enter a password interactively

In the argparse module, the input password can only be set as a normal parameter, which will bring certain security risks: our password can be easily obtained by using history.

In click, the above problems have been solved beautifully: you can enter the password interactively by setting prompt=True; Set hide_input=True to hide our command line input; Set confirmation_prompt=True to verify the password twice.

import click
from werkzeug.security import generate_password_hash

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

if __name__ == '__main__':
    encrypt()

Operation results:

 

Example 5 editing input data in the editor

Users familiar with Linux system may have used the command fc, which is very convenient when editing long commands. Enter the fc command and press enter to open an editor that has saved the contents of the previous command. We just need to fix the error content in the editor, then save and exit. The command just edited will be executed automatically.

 

Using the Click library, similar functions can be implemented in Python:

from __future__ import print_function
import click
import os

message = click.edit()
print(message)
print(os.system(message))

Run the code and the program will automatically enter the default editor. After entering the editor, you can edit the input data in the editor, and the input content will be assigned to the variable message in the program:

 

Note: Click is an excellent open source project. For more details, please refer to Click's official website: https://click.palletsprojects.com/en/8.0.x/

Topics: Python Flask