Click
[Click][0] is another open source project from [Flask][1]'s development team [Pallets][2], which is a third-party module for quickly creating command lines. We know that Python has a built-in standard library of [Argparse][3] for creating command lines, but it is a bit cumbersome to use. [Click][0] is compared to [Argparse][3], just like [requests][4] and [urllib][5].
Quick use
There are roughly two steps to use Click:
- use
@()
Decorate a function to make it a command line interface; - use
@()
etc., add command line options, etc.
One of its typical uses is as follows:
import click @() @('--param', default=default_value, help='description') def func(param): pass
Below, let's take a look at the introductory example of [official document][6]:
import click @() @('--count', default=1, help='Number of greetings.') @('--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): ('Hello %s!' % name) if __name__ == '__main__': hello()
In the above example, the functionhello
There are two parameters: count and name, whose values are taken from the command line.
-
@()
Make a functionhello
Become a command line interface; -
@
The first parameter of the command line option specifies the name of the command line option. It is not difficult to guess that the default value of count is 1, and the value of name is obtained from the input; - use
The output is done for better compatibility, because
print
There are some differences in usage in Python2 and Python3.
Check out the implementation:
$ python Your name: Ethan # Here will display 'Your name: '(prompt in the corresponding code), accept user inputHello Ethan! $ python --help # click automatically generated `--help` usageUsage: [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 --count 3 --name Ethan # Specify the values of count and nameHello Ethan! Hello Ethan! Hello Ethan! $ python --count=3 --name=Ethan # You can also use `=`, which is equivalent to the aboveHello Ethan! Hello Ethan! Hello Ethan! $ python --name=Ethan # No count is specified, the default value is 1Hello Ethan!
The most basic usage of option is to specify the name of the command line option, read the parameter value from the command line, and then pass it to the function. In the above example, we see that in addition to setting the name of the command line option, we will also specify the default value, help description, etc. The commonly used setting parameters of option are as follows:
- default: Set the default value of command line parameters
- help: Parameter description
- type: parameter type, can be string, int, float, etc.
- prompt: When no corresponding parameters are entered in the command line, the user will be prompted to enter according to prompt
- nargs: Specify the number of values received by command line parameters
Let’s take a look at related examples.
Specify type
We can usetype
To specify the parameter type:
import click @() @('--rate', type=float, help='rate') # Specify that rate is float typedef show(rate): ('rate: %s' % rate) if __name__ == '__main__': show()
Implementation status:
$ 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 values. If the user enters other values, we should prompt the user to enter the correct value. In this case, we can()
To limit:
import click @() @('--gender', type=(['man', 'woman'])) # Limit valuedef choose(gender): ('gender: %s' % gender) if __name__ == '__main__': choose()
Implementation status:
$ 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
Multi-value parameters
Sometimes, a parameter needs to receive multiple values.option supports setting parameter values of fixed length,passnargs
Specified.
Just look at the examples and understand:
import click @() @('--center', nargs=2, type=float, help='center of the circle') @('--radius', type=float, help='radius of the circle') def circle(center, radius): ('center: %s, radius: %s' % (center, radius)) if __name__ == '__main__': circle()
In the above example, option specifies two parameters: center and radius, where center represents the center coordinates of a circle on a two-dimensional plane, receives two values, and passes the value to the function in the form of a tuple, while radius represents the radius of the circle.
Implementation status:
$ 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)
Enter your password
Sometimes, when entering a password, we want to hide the display. option provides two parameters to set the input of the password: hide_input and confirmation_promt, where hide_input is used to hide the input and confirmation_promt is used to repeat the input.
Take a look at the example:
import click @() @('--password', prompt=True, hide_input=True, confirmation_prompt=True) def input_password(password): ('password: %s' % password) if __name__ == '__main__': input_password()
Implementation status:
$ python click_password.py Password: # Password not displayedRepeat for confirmation: # Repeatpassword: 666666
Since the above writing method is a bit cumbersome, click also provides a quick way to use it@click.password_option()
, the above code can be abbreviated as:
import click @() @click.password_option() def input_password(password): ('password: %s' % password) if __name__ == '__main__': input_password()
Change the execution of the command line program
Some parameters will change the execution of the command line program, such as inputting it in the terminal.python
It is to enter the python console and enterpython --version
is to print the python version. Click provides the eager identifier to identify the parameter name. If you enter this parameter, it will intercept the established command line execution process and jump to execute a callback function.
Let's look at the example:
import click def print_version(ctx, param, value): if not value or ctx.resilient_parsing: return ('Version 1.0') () @() @('--version', is_flag=True, callback=print_version, expose_value=False, is_eager=True) @('--name', default='Ethan', help='name') def hello(name): ('Hello %s!' % name) if __name__ == '__main__': hello()
in:
-
is_eager=True
Indicates that the command line option has a higher priority than other options; -
expose_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 be executed when entering this command line option;
Implementation status:
$ python click_eager.py Hello Ethan! $ python click_eager.py --version # Intercept the established command line execution processVersion 1.0 $ python click_eager.py --name Michael Hello Michael! $ python click_eager.py --version --name Ethan # Ignore the name optionVersion 1.0
In addition to using@
To addOptional parameters, will also be used frequently@
To addFixed parameters. It uses similar to option, but supports fewer functions than option.
Getting started
Here is a simple example:
import click @() @('coordinates') def show(coordinates): ('coordinates: %s' % coordinates) if __name__ == '__main__': show()
Check out the implementation:
$ python click_argument.py # Error, missing parameter coordinatesUsage: click_argument.py [OPTIONS] COORDINATES Error: Missing argument "coordinates". $ python click_argument.py --help # argument specified in the argument is not displayed in helpUsage: click_argument.py [OPTIONS] COORDINATES Options: --help Show this message and exit. $ python click_argument.py --coordinates 10 # Error usage, this is the usage of option parameterError: no such option: --coordinates $ python click_argument.py 10 # Correct, just enter the valuecoordinates: 10
Multiple arguments
Let's take a look at several examples of arguments:
import click @() @('x') @('y') @('z') def show(x, y, z): ('x: %s, y: %s, z:%s' % (x, y, z)) if __name__ == '__main__': show()
Implementation status:
$ 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)
Undetermined parameters
There is another common usage of argument, which is to receive irregular parameters. Let's take a look at the example:
import click @() @('src', nargs=-1) @('dst', nargs=1) def move(src, dst): ('move %s to %s' % (src, dst)) if __name__ == '__main__': move()
in,nargs=-1
Indicate parameterssrc
Receives an indefinite parameter value, and the parameter value will be passed into the function in the form of a tuple. ifnargs
greater than or equal to 1 means receivingnargs
parameter values, in the example above,dst
Receive a parameter value.
Let's see how the execution is:
$ 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 useIf we use the [colorama][7] module, we can use
For color output, use pip to install colorama before using:
$ pip install colorama
Take a look at the example:
import click @() @('--name', help='The person to greet.') def hello(name): ('Hello %s!' % name, fg='red', underline=True) ('Hello %s!' % name, fg='yellow', bg='black') if __name__ == '__main__': hello()
in:
-
fg
It represents the foreground color (i.e. font color), optional values include: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, etc.; -
bg
It represents the background color, optional values include: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, etc.; -
underline
Indicates underline, optional styles include:dim=True
,bold=True
wait;
summary
- use
()
Decorate a function to make it a command-line interface. - use
()
Add optional parameters to support setting parameter values of fixed lengths. - use
()
Add fixed parameters, supporting setting parameter values of uncertain lengths.
This is all about this article about Python third-party library Click. For more related content on Python third-party library Click, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!