Quick Start Python command-line module Click

Quick Start Python command-line module Click

About Click?

Click the module is that the next Gansha, simply put, it is the function of some of our Python script, by
decorated decorator with Click to add keywords and then the function call form into the form of parameter passing command line and then carried out. Do not understand it does not matter, we'll go step by step, essentially according to my actual application to write.
This article does not involve too much complex grammar and theory, will use simple language and we share.

installation

python3 -m pip install click

A simple example

First we create a demo.py

import click #(1)
@click.command() #(2)
def main():
    click.echo("hello click") #(3)

if __name__ == '__main__':
    main()

Decorators @click.command()will click into our function package objects, then we can call methods in the click function, is used click.echo, its role is similar to our Print, the output.
By command line so that we can run this line of code

python3 demo.py

Well, our first example of a get away, we found this time without the use of click code uses seems to be no difference.
Next we were to expand it, and if we need to pass a number, and then print this time, we can write the code.

Our first argument passed

import click

@click.command()
@click.option("-n", "--num", help="input a num")
def main(num):
    click.echo(f"{num =}")

if __name__ == '__main__':
    main()

Here's the basis of our previous code adds to the function main @click.optiondecorator.

Went on to say under the meaning of these parameters
-n : means that we can use it, when attention is a short command line parameter to specify the name of the '-'
--num : is the full name of the first argument, we when the value of the received program using it. Note that two short '-'.
Help : At the command line, type "python3 demo.py --help" when it can prompt us to this program which commands can be used. And we use the command line a reason.
Then our main function is the parameter name, the full name of the parameter we want to receive, and printed out click.echo. , f"{num=}"Syntactic sugar after Python 3.8, num = 3 if it is equivalent to the num = 3.
Finally, remember that in __main__the implementation of our main method inside.
Well, introduced over the code, we can run, and run the example:
First, do not assume that we know it has several parameters.

python3 demo.py --help 

By help we can get the following information

Usage: demo.py [OPTIONS]

Options:
  -n, --num TEXT  input a num  #这是定义该字段help的提示内容
  --help          Show this message and exit.

Usage: corresponds to our current filename
Options: is a line of argument, an argument divided - full parameter names beginning - the beginning of the abbreviated parameter, and.
Back then we can see that it is of type TEXT. Followed by that prompted the parameter information through the help we can set.

 python3 demo.py -n 3
 #输出
 num ='3'

or

 python3 demo.py --num 3
 #输出
 num ='3'

The above two methods are equivalent input by using any line.

Now think about a problem, if we need the type of numeric value num 3 how to get it?

Declare the parameter type

Here are two ways to provide (of course not both) of
Method One: Use the type keyword, type in the type that python

@click.option("-n", "--num",type=int,help="input a num")

Execute the code again

 python3 demo.py -n 4
 #输出
 num =4

While viewing help information when TEXT become the INTEGER.
Method Two: Use the default keyword, specify a default value of 1

@click.option("-n", "--num",default=1,help="input a num")

The default value is set to digital, we will know that we command line parameter of type int,
where the processing parameters specified type, also set default values. Set as a parameter default values, you can not specify its value, this time will use the default value.
If we use help find and view information above method a little different. At this time we can by specifying another keyword, it displays help information in the default value

@click.option("-n", "--num",default=1,help="input a num",show_default=True)

We can make by adding show_default default value is displayed in the help information, content format as follows:

Usage: demo.py [OPTIONS]

Options:
  -n, --num INTEGER  input a num  [default: 1]
  --help             Show this message and exit.

Coupled with a parameter

Modify the code portion of the code on the basis of the above, the main parameter is to add a new id.

import click


@click.command()
@click.option("-i", "--id", required=True, help="input an id")
@click.option("-n", "--num", type=int, help="input  a number", show_default=True)
def main(id, num):
    click.echo(f"your {id=} {num=}")

if __name__ == '__main__':
    main()

Before the function to add @click.optiondecoration can be.
Here I add a parameter for the id, id is because under normal circumstances can not be empty, so we can required = Truelimit it, it indicates that the parameter is mandatory pass parameters. If you do not pass on errors

python3 demo.py -n 1234 
#没给id传参,出现错误,提示缺少参数。
Usage: demo.py [OPTIONS]
Try "demo.py --help" for help.

Error: Missing option "-i" / "--id".

Proper use should be

python3 demo.py -i 1 -n 1234

So far a short-answer command-line tool is generated. I went on to say at what it did.

Deal with real problems

Now we have a need to find the corresponding user name to mongo database user login information, and ultimately generate information in the following format:

不好意思人太多了,让您久等了,您的信息来了!
**************************************************
用户名:lisa
密码: 1234qwer
登录网站: http://www.xxxx.com
**************************************************️
目前密码唯一的不要修改哦!
该条消息不用回复了,谢谢。

I was a beginning, and then by adding a configuration file in python script in the form of profiles modify the user name, but this approach is not flexible, every time need to re-run Python code. Or we can use to build a RESTful api fastapi service, but I'm too lazy to take the service. Finally, I chose to use the command line to run the form. Module is used today said this click the module.
Then write a code is needed:

@click.command()
@click.option('-u', '--user_name', type=str, help='search user_name')
def main(user_name):
    click.echo(f'search user:{user_name}')
    result = m.get_user_info(user_name) #数据库查询
    try:
        info = f"不好意思人太多了,让您久等了,您的信息来了!\n{'*' * 50}\n用户名: {result.get('user_name')}\n" \
            f"密码: {result.get('user_pwd')}\n登录网站: {result.get('url')}\n{'*' * 50}️\n目前密码唯一的不要修改哦!\n该条消息不用回复了,谢谢。"
    except Exception as e:
        info = "Not Found"
    click.echo(info)


if __name__ == '__main__':
    main()

We can be queried by the above code in the form of the command line.

python3 demo.py -u 1234

Very convenient.
If this time, I need to add a temporary user features, you need to write a function, and
then how we can control the operation of the two functions of the command line it? This is going to say next group.

Create a form of group

Create a group called, the main entrance is through a function, related to other functions, and other functions can be used directly as a command name.
Well, first create a main entry function

@click.group()
def main():
   pass

This time we noticed that the main changes to the above decorator @click.group().
Through it we are ready to create a command-line group. Next, we started creating group members, group members is a so-called function.

@main.command()
@click.option('-u', '--user_name', type=str, help='add user_name')
def get_user(user_name):
     click.echo(f'search user:{user_name}')

The role of the members of the group and its name is the same function that queries user information.
It should be noted that members of the group from the original decorators
@click.commandbecomes a @main.command.
main is the main method name above. Then following the same option is to declare some parameters.
Next we create a second group member, to add user information.

@main.command()
@click.option('-u', '--user_name', required=True, type=str, help="要添加的用户名")
@click.option('-p', '--password', required=True, type=str, help="要添加的密码")
@click.option('-t', '--id_type', required=True, default="phone", type=str, help="添加的账户类型",show_default=True)
def add_user(user_name, password, id_type):
     #do something.....
     click.echo(f"{user_name=}  {password=} {id_type=}")

First, by @main.command()adding it to the group. Then is the option to add a series of operating parameters. The specific parameters of said information not mentioned above here. Well, we created two members,
if you need other functions, such as delete user, you can continue to add a delete_user function, and so on.

Now I say, how to perform under the above two member functions.

First, look at it under the help command, are what generally do not know there is a command-line application when what I command parameters we can use it.

python3 demo.py --help

The following output

Usage: demo.py [OPTIONS] COMMAND [ARGS]...

Options:
  --help  Show this message and exit.

Commands:
  add-user
  get-user

Commands command which is to call a function of our members, we will need to look at the original function "_" to a "-."
Then we can call the query method

python3 demo.py get-user -u 123

Then we can get the result

search user:123

The same method call to add user information.

python3 demo.py add-user -u 123 -p "1234qwer"

Because -tnot necessarily pass parameters so we can ignore, use the default value of "phone".
Well, this is content to say today, basically enough for the daily operations.

More content, interested friends can refer to the official documentation.

Guess you like

Origin www.cnblogs.com/c-x-a/p/12461646.html