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

The best Python command line library to use: Click

編輯:Python

One 、 Preface
What I want to introduce today click[2] It's a familiar way to play around the command line . Command line programs are essentially defining parameters and processing parameters , The logic of processing parameters must be related to the defined parameters . Can we use functions and decorators to realize the relationship between processing parameter logic and defining parameters ? and click It's exactly in this way that .

This series uses... By default Python 3 Explain as an interpreter .
If you are still using Python 2, Please pay attention to the differences between the syntax and the use of the library ~

Two 、 Introduce
click Is a code with as little code as possible 、 To create graceful command line programs in a combined way Python package . It's highly configurable , It can also be used out of the box .

It's designed to make the process of writing command-line tools quick and fun , It can also prevent the failure to achieve the expected CLI API A sense of frustration . It has the following three characteristics :

  • Any nested command
  • Automatically generate help
  • Supports runtime delay loading subcommands

3、 ... and 、 Quick start
3.1 Business logic
First define the business logic , Don't you feel some disbelief ?

Whether it's argparse still docopt, Business logic is all put in the last step , but click But in the first step . Think about it click This way is more in line with people's thinking ? No matter what command-line framework you use , Our ultimate concern is to implement business logic , Other energy savings are less .

Let's take the official example , To introduce click Usage and philosophy of . Suppose the input to the command line program is name and count, The function is to print the name of a specified number of times .

So in hello.py in , It's easy to write the following code :

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)

The logic of this code is very simple , It's a cycle count Time , Use click.echo Print name. among ,click.echo and print It's similar , But it's more powerful , Can handle Unicode and Binary data .

3.2 Defining parameters
Obviously , We need to target count and name To define their corresponding parameter information .

  • count Corresponding to command line options --count, The type is number , We hope that when we do not provide parameters , The default value is 1

  • name Corresponding to command line options --name, Type is string , We hope that when we do not provide parameters , Can give a hint
    Use click, It can be written as follows :

    from click 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): ...

In the example above :

  • How to use decorators , That is, the parameters are defined , And bind it to the processing logic , It's so elegant . and argparse、docopt Compare to , One less step in the binding process
  • Use click.command Express hello It's the handling of orders
  • Use click.option To define parameter options
  • about --count Come on , Use default To specify the default . And because the default value is number , And then it suggests that --count The type of option is number
  • about --name Come on , Use prompt To specify the prompt when this option is not entered
  • Use help To specify help information

No matter the way of decorating 、 Or default behavior ,click It's all like its introduction , Let people write as little code as possible , Make the whole process fast and fun .

3.3 Code hacking
Use click It's very simple , Let's summarize the above code , To have a clearer understanding of :

# hello.py
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()

If we specify times and names :

$ python3 hello.py --count 2 --name Eric
Hello Eric!
Hello Eric!

If we don't specify anything , You will be prompted to enter a name , And default output once :

$ python3 hello.py
Your name: Eric
Hello Eric!

We can also go through --help Parameter to view automatically generated help information :

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.

Four 、 Summary
click The idea is very simple , Define processing functions , Define parameters through its decorator . The great thing about using decorators is to combine the two steps of definition and binding into one step , Make the whole process silky .

click Except for Pythonic This method makes the implementation of the command-line program more elegant and easy to use , There are also offers argparse and docopt All need powerful functions .

The above is all the content shared this time , Want to know more python Welcome to official account :Python Programming learning circle , send out “J” Free access to , Daily dry goods sharing


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