程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

[Python] Click module development command line application

編輯:Python

Bowen author wangzirui32
Like can give the thumbs-up Collection Pay attention to ~~
This article was first published in CSDN, Reprint is prohibited without permission


hello, Hello everyone , I am a wangzirui32, Today we are going to study click Module development command line application , Start learning !

Catalog

  • 1. click
  • 2. Hello World The first example
  • 3. click.option Decorator
  • 4. click.Choice Select parameters
  • 5. click.secho Output

1. click

click The introduction is as follows ( From official documents ):

The installation command is as follows :

pip install click

2. Hello World The first example

After confirming that the installation is correct , Start learning . establish hello.py, Write code :

import click
# Command group 
group = click.Group()
# Definition hello command 
@click.command("hello")
def hello():
click.echo("Hello User ! Welcome !")
# add to hello command 
group.add_command(hello)
group.main() # Enable intra group commands 

Let's parse the code step by step :

  1. import click Import click modular
  2. group = click.Group() The command group is defined group, It is used to store commands defined in the program .
  3. @click.command("hello") This is a decorator ,"hello" Represents its command name .
  4. def hello(): Definition hello function .
  5. click.echo("Hello User ! Welcome !") Output greeting message , It's used here click.echo Output , According to official documents , This function is better than the original print More powerful , Support more output functions , Recommended .
  6. group.add_command(hello) hold hello Names are added to the command group .
  7. group.main() Enable the commands added in the Group .

Let's see the effect :

PS D:\Python> python hello.py hello
Hello User ! Welcome !

See we entered python hello.py hello Represents a call to hello.py Medium hello name , Then I output greetings .

3. click.option Decorator

Or just now , Just some code changes :

import click
group = click.Group()
@click.command("hello")
@click.option("--username") # Add parameters username
def hello(username): # Function parameters are added username
# Output pair username Greetings from 
click.echo("Hello {}! Welcome!".format(username))
group.add_command(hello)
if __name__ == '__main__':
group.main()

The effect is as follows :

PS D:\Python> python hello.py hello --username Malfoy
Hello Malfoy! Welcome!

In the example above , We added parameters username, Take a look at the key line of code @click.option("--username"), It means adding a command named username Parameters of , It is specified in the command line as --username.
Of course , There are other parameters of this decorator , Let's move on to the following example :

import click
group = click.Group()
@click.command("hello")
@click.option("--username", default="wangzirui32", help=" user name ")
@click.option("--email", prompt=" Your email : ", help=" mailbox ")
@click.option('--password', prompt=True,
hide_input=True, confirmation_prompt=True, help=" password ")
def hello(username, email, password):
click.echo("Hello {}! Welcome! Your email is {}".format(username, email))
click.echo("Password: {}".format(password))
group.add_command(hello)
if __name__ == '__main__':
group.main()

The effect is as follows :

PS D:\Python>python hello.py hello --email [email protected]***.com
Password:
Repeat for confirmation:
Hello wangzirui32! Welcome! Your email is [email protected]***.com
Password: 123456

Let's analyze 3 Codes :

  1. @click.option("--username", default="wangzirui32", help=" user name ") In this line of code , We have designated username The default parameters of and its help information , Can pass --help Command view .
  2. @click.option("--email", prompt=" Your email : ", help=" mailbox ") In this line of code , We have designated prompt Parameters , It means that if we do not specify email, When the program is running, output prompt words to prompt for input .
  3. @click.option('--password', prompt=True,hide_input=True, confirmation_prompt=True, help=" password ") This line of code specifies the password parameters ,prompt=True Allow the program to output prompts for input when running ,hide_input Hide input ,confirmation_prompt=True It is required to verify the password entered before , Finally, specify help information , In fact, it is equivalent to code click.password_option().
    Let me just say a word here , Help information is click One of the highlights , To access help, you can use --help, Examples are as follows :
PS D:\Python> python hello.py hello --help
Usage: hello.py hello [OPTIONS]
Options:
--username TEXT user name
--email TEXT mailbox
--password TEXT password
--help Show this message and exit.
PS D:\Python> python hello.py --help
Usage: hello.py [OPTIONS] COMMAND [ARGS]...
Options:
--help Show this message and exit.
Commands:
hello

There are other parameters of this decorator , I won't go into that , The author has compiled it into the following table :

Parameter name Parameter Introduction default Specify default help Specify help information type Specify the data type of the parameter ( Such as str,float)required Whether it is required ,True Is required prompt Prompt the user to enter the information of the corresponding option on the command line nargs Specify the number of parameters this command receives , More than will report error

4. click.Choice Select parameters

Let's start with an example ,Code:

import click
group = click.Group()
@click.command("hello")
@click.option("--fruit", type=click.Choice(['apple', 'orange', 'grapes'])) # Defined as selection parameter 
def hello(fruit):
click.echo(" Fruits :{}".format(fruit))
group.add_command(hello)
if __name__ == '__main__':
group.main()

Running effect :

PS D:\Python> python hello.py hello --fruit apple
Fruits :apple

It's used here click.Choice Pass in the list of options , And then take it as a parameter type Pass in click.option, It's done. , If you enter a value that is not in the option list , The program will report an error .

5. click.secho Output

We introduced it above click.echo Output mode of , But in click There is another output function in click.secho, Look at code :

import click
group = click.Group()
@click.command("hello")
def hello():
click.secho("Hello!", fg="green")
click.secho(" Hello !", fg="red")
group.add_command(hello)
if __name__ == '__main__':
group.main()

Output :

click.secho You can output text with color , In fact, this code is equivalent to :

click.echo(click.style("Hello!", fg="green"))
click.echo(click.style(" Hello !", fg="red"))

The effect is the same .


Okay , That's all for today's lesson , I am a wangzirui32, You can collect and pay attention to what you like , See you next time !


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved