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

Python is a super easy-to-use command-line interface implementation tool. I guarantee you dont know

編輯:Python

Preface

Click It is a simple and easy to use Python modular , It can achieve a beautiful command-line interface with as little code as possible . It's not just out of the box 、 It also supports highly customized configuration

Set up .

 Official documents :https://click.palletsprojects.com/en/8.0.x/

A simple example is as follows :

import click
PYTHON plug-in unit / material / Source code plus Q Group :903971231####
@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(f"Hello {
name}!")
if __name__ == '__main__':
hello()

The effect is as follows :

It can be seen that this module is powerful , You just need to add a few decorators to the corresponding function , You can create a command line interface with a prompt , Quite convenient .

1. Get ready

First, you need to install your computer Python Environmental Science , And it's installed Python development tool .

Please choose one of the following ways to enter the command to install the dependency :

1. Windows Environmental Science open Cmd ( Start - function -CMD).
2. MacOS Environmental Science open Terminal (command+ Space input Terminal).
3. If you're using a VSCode Editor or Pycharm, You can directly use the Terminal.
pip install click

2. Basic use

As the example shown at the beginning of the text ,@click.option Is the most basic option , It can set the default value of parameters , You can also set the parameters that must be passed in :

@click.command()
@click.option('--n', default=1) # Default values are set 
def dots(n):
click.echo('.' * n)
@click.command()
@click.option('--n', required=True, type=int) # Set the parameter value that must be passed in 
def dots(n):
click.echo('.' * n)

If you set, you must pass in relevant parameters , So without passing in parameters , The effect is this :

Of course , It also supports setting multiple parameter aliases , Like the following --from and -f It's equivalent :

@click.command()
@click.option('--from', '-f', 'from_')
@click.option('--to', '-t')
def reserved_param_name(from_, to):
click.echo(f"from {
from_} to {
to}")


3. Multivalued parameters

If your option requires multiple parameters ,Click It can also help you realize this demand .

@click.command()
@click.option('--pos', nargs=2, type=float)
def findme(pos):
a, b = pos
click.echo(f"{
a} / {
b}")

so , By configuring nargs Parameters , You can store the values passed by the user in tuples , And unpack the tuple in the code to get all the values .

The effect is as follows :

You can also configure a parameter called multiple, This parameter allows you to accept N It's worth :

@click.command()
@click.option('--message', '-m', multiple=True)
def commit(message):
click.echo(' '.join(message))

4. Other features

You can still use it Click To count , This use is very rare :

@click.command()
@click.option('-v', '--verbose', count=True)
def log(verbose):
click.echo(f"Verbosity: {
verbose}")

The effect is as follows :

The Boolean sign

Besides ,Click It also has boolean flag function , You can use it directly “/” To mark that the parameter is one of two , Boolean variables will be directly obtained in the function :

import sys
python plug-in unit / Source code / Material plus Q Group :903971231###
@click.command()
@click.option('--shout/--no-shout', default=False)
def info(shout):
rv = sys.platform
if shout:
rv = rv.upper() + '!!!!111'
click.echo(rv)

Select options

You can directly limit the user's input range :

@click.command()
@click.option('--hash-type',
type=click.Choice(['MD5', 'SHA1'], case_sensitive=False))
def digest(hash_type):
click.echo(hash_type)

Tip text

In the example mentioned at the beginning of the article , Output a “You name:” A hint of , It's actually option Medium prompt Parameter controlled :

@click.command()
@click.option('--name', prompt='Your name please')
def hello(name):
click.echo(f"Hello {
name}!")

Last

Okay ,Click That's all for the function of , He also has many advanced uses , For example, dynamic defaults 、 Callback functions, etc , You can learn about these high standards through official documents

How to use level-1 functions :

https://click.palletsprojects.com/en/8.0.x/options/#name-your-options


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