日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

python Click库知识点汇总

發(fā)布時(shí)間:2023/12/18 python 25 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python Click库知识点汇总 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

Python Click庫(kù)
作用:用于快速創(chuàng)建命令行,或者說,通過裝飾器@click.command(把一個(gè)函數(shù)方法裝飾成命令行接口。

  • 安裝:
$ pip install click
  • 如何使用:

基礎(chǔ)方法:裝飾器函數(shù)

  • 使用@click.command() 裝飾一個(gè)函數(shù),使之成為命令行接口
  • 使用@click.option() 裝飾函數(shù),為其添加命令行選項(xiàng)
  • 使用@click.argument()裝飾函數(shù),為其添加命令行選項(xiàng)
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.""" # 會(huì)當(dāng)作help信息進(jìn)行輸出for x in range(count):click.echo('Hello %s!' % name)if __name__ == '__main__':hello()

將上面的代碼保存為hello.py,在終端中運(yùn)行:

python3 hello.py --help 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.
  • argument與option

argument() 裝飾器比 option() 功能簡(jiǎn)單些,后者支持下面的特性:

自動(dòng)提示缺失的輸入; option 參數(shù)可以從環(huán)境變量中獲取,argument 參數(shù)則不行; option 參數(shù)在 help 輸出中有完整的文檔,argument 則沒有;

而 argument 參數(shù)可以接受可變個(gè)數(shù)的參數(shù)值,而 option 參數(shù)只能接收固定個(gè)數(shù)的參數(shù)值(默認(rèn)是 1 個(gè))。

命令行的參數(shù)名由 “-short_name” 或 “–long_name” 聲明,如果參數(shù)名既沒有以 “-“ 開頭,也沒有以 “–” 開頭
關(guān)于命令行參數(shù),以前綴“-”開頭,和以前綴“–”(兩個(gè)連續(xù)短橫線)開頭,或者不帶任何前綴開頭的區(qū)別,參考原文:
Parameters

Parameter NamesParameters (both options and arguments) accept a number of positional arguments which are passed to the command function as parameters. Each string with a single dash is added as a short argument; each string starting with a double dash as a long one.If a string is added without any dashes, it becomes the internal parameter name which is also used as variable name.If all names for a parameter contain dashes, the internal name is generated automatically by taking the longest argument and converting all dashes to underscores.The internal name is converted to lowercase.Examples:For an option with ('-f', '--foo-bar'), the parameter name is foo_bar.For an option with ('-x',), the parameter is x.For an option with ('-f', '--filename', 'dest'), the parameter name is dest.For an option with ('--CamelCaseOption',), the parameter is camelcaseoption.For an arguments with (`foogle`), the parameter name is foogle. To provide a different human readable name for use in help text, see the section about Truncating Help Texts.
  • Option

option 最基礎(chǔ)的用法就是簡(jiǎn)單值變量,option 接收一個(gè)變量值,下面是一段示例代碼:

@click.command() @click.option('--n', default=1) def dots(n):click.echo('.' * n)

如果在命令行后面跟隨參數(shù) --n=2 就會(huì)輸出兩個(gè)點(diǎn),如果傳參數(shù),默認(rèn)輸出一個(gè)點(diǎn)。上面的代碼中,參數(shù)類型沒有顯示給出,但解釋器會(huì)認(rèn)為是 INT 型,因?yàn)槟J(rèn)值 1 是 int 值。
有些時(shí)候需要傳入多個(gè)值,可以理解為一個(gè) list,option 只支持固定長(zhǎng)度的參數(shù)值,即設(shè)置后必須傳入,個(gè)數(shù)由 nargs 確定。

@click.command() @click.option('--pos', nargs=2, type=float) def findme(pos):click.echo('%s / %s' % pos)# findme --pos 2.0 3.0 輸出結(jié)果就是 2.0 / 3.0

既然可以傳入 list,那么 tuple 呢?Click 也是支持的:

@click.command() @click.option('--item', type=(unicode, int)) def putitem(item):click.echo('name=%s id=%d' % item)""" 這樣就傳入了一個(gè) tuple 變量 putitem --item peter 1338 得到的輸出就是 name=peter id=1338 """

上面沒有設(shè)置 nargs,因?yàn)?nargs 會(huì)自動(dòng)取 tuple 的長(zhǎng)度值。因此上面的代碼實(shí)際上等同于:

@click.command() @click.option('--item', nargs=2, type=click.Tuple([unicode, int])) def putitem(item):click.echo('name=%s id=%d' % item)

option 還支持同一個(gè)參數(shù)多次使用,類似 git commit -m aa -m bb 中 -m 參數(shù)就傳入了 2 次。option 通過 multiple 標(biāo)識(shí)位來支持這一特性:

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

有時(shí)候,命令行參數(shù)是固定的幾個(gè)值,這時(shí)就可以用到 Click.choice 類型來限定傳參的潛在值:

# choice @click.command() @click.option('--hash-type', type=click.Choice(['md5', 'sha1'])) def digest(hash_type):click.echo(hash_type)

當(dāng)上面的命令行程序參數(shù) --hash-type 不是 md5 或 sha1,就會(huì)輸出錯(cuò)誤提示,并且在 --help 提示中也會(huì)對(duì) choice 選項(xiàng)有顯示。

如果希望命令行程序能在我們錯(cuò)誤輸入或漏掉輸入的情況下,友好的提示用戶,就需要用到 Click 的 prompt 功能,看代碼:

# prompt @click.command() @click.option('--name', prompt=True) def hello(name):click.echo('Hello %s!' % name)

如果在執(zhí)行 hello 時(shí)沒有提供 –name 參數(shù),控制臺(tái)會(huì)提示用戶輸入該參數(shù)。也可以自定義控制臺(tái)的提示輸出,把 prompt 改為自定義內(nèi)容即可。

對(duì)于類似賬戶密碼等參數(shù)的輸入,就要進(jìn)行隱藏顯示。option 的 hide_input 和 confirmation_promt 標(biāo)識(shí)就是用來控制密碼參數(shù)的輸入:

# password @click.command() @click.option('--password', prompt=True, hide_input=True,confirmation_prompt=True) def encrypt(password):click.echo('Encrypting password to %s' % password.encode('rot13'))

Click 把上面的操作進(jìn)一步封裝成裝飾器 click.password_option(),因此上面的代碼也可以簡(jiǎn)化成:

# password @click.command() @click.password_option() def encrypt(password):click.echo('Encrypting password to %s' % password.encode('rot13'))

有的參數(shù)會(huì)改變命令行程序的執(zhí)行,比如 node 是進(jìn)入 Node 控制臺(tái),而 node --verion 是輸出 node 的版本號(hào)。Click 提供 eager 標(biāo)識(shí)對(duì)參數(shù)名進(jìn)行標(biāo)記,攔截既定的命令行執(zhí)行流程,而是調(diào)用一個(gè)回調(diào)方法,執(zhí)行后直接退出。下面模擬 click.version_option() 的功能,實(shí)現(xiàn) --version 參數(shù)名輸出版本號(hào):

# eager def print_version(ctx, param, value):if not value or ctx.resilient_parsing:returnclick.echo('Version 1.0')ctx.exit() @click.command() @click.option('--version', is_flag=True, callback=print_version,expose_value=False, is_eager=True) def hello():click.echo('Hello World!')

對(duì)于類似刪除數(shù)據(jù)庫(kù)表這樣的危險(xiǎn)操作,Click 支持彈出確認(rèn)提示,–yes 標(biāo)識(shí)位置為 True 時(shí)會(huì)讓用戶再次確認(rèn):

# yes parameters def abort_if_false(ctx, param, value):if not value:ctx.abort() @click.command() @click.option('--yes', is_flag=True, callback=abort_if_false,expose_value=False,prompt='Are you sure you want to drop the db?') def dropdb():click.echo('Dropped all tables!')

測(cè)試運(yùn)行下:

$ dropdb Are you sure you want to drop the db? [y/N]: n Aborted! $ dropdb --yes Dropped all tables!

同樣的,Click 對(duì)次進(jìn)行了封裝,click.confirmation_option() 裝飾器實(shí)現(xiàn)了上述功能:

@click.command() @click.confirmation_option(prompt='Are you sure you want to drop the db?') def dropdb():click.echo('Dropped all tables!') # range @click.command() @click.option('--count', type=click.IntRange(0, 20, clamp=True)) @click.option('--digit', type=click.IntRange(0, 10)) def repeat(count, digit):click.echo(str(digit) * count) if __name__ == '__main__':repeat()
  • 關(guān)于is_flag
    Option的關(guān)鍵字參數(shù)中,有is_flag 參數(shù),默認(rèn)值是None,如果設(shè)置了該參數(shù),即is_flag=True,則表示Option函數(shù)定義的參數(shù)為“標(biāo)記”參數(shù)。
    原文:
    is_flag – forces this option to act as a flag. The default is auto detection.

例子:

import click @app.cli.command() # 注冊(cè)為命令 @click.option('--drop', is_flag=True, help='Create after drop.') # 設(shè)置選項(xiàng) def initdb(drop): """Initialize the database.""" if drop: # 判斷是否輸入了選項(xiàng) db.drop_all() db.create_all() click.echo('Initialized database.') # 輸出提示信息

運(yùn)行結(jié)果:
默認(rèn)情況下,函數(shù)名稱就是命令的名字,現(xiàn)在執(zhí)行 flask initdb 命令就可以創(chuàng)建數(shù)據(jù)庫(kù)表:

$ flask initdb

使用 --drop 選項(xiàng)可以刪除表后重新創(chuàng)建:

$ flask initdb --drop

is_flag原文文檔請(qǐng)參考:is_flag

  • Argument

Argument 的作用類似 Option,但沒有 Option 那么全面的功能。

和 Option 一樣,Argument 最基礎(chǔ)的應(yīng)用就是傳遞一個(gè)簡(jiǎn)單變量值:

@click.command() @click.argument('filename') def touch(filename):click.echo(filename)

命令行后跟的參數(shù)值被賦值給參數(shù)名 filename。

另一個(gè)用的比較廣泛的是可變參數(shù),也是由 nargs 來確定參數(shù)個(gè)數(shù),變量值會(huì)以 tuple 的形式傳入函數(shù):

@click.command() @click.argument('src', nargs=-1) @click.argument('dst', nargs=1) def copy(src, dst):for fn in src:click.echo('move %s to folder %s' % (fn, dst))

運(yùn)行程序:

$ copy foo.txt bar.txt my_folder move foo.txt to folder my_folder move bar.txt to folder my_folder

Click 支持通過文件名參數(shù)對(duì)文件進(jìn)行操作,click.File() 裝飾器就是處理這種操作的,尤其是在類 Unix 系統(tǒng)下,它支持以 - 符號(hào)作為標(biāo)準(zhǔn)輸入/輸出。

# File @click.command() @click.argument('input', type=click.File('rb')) @click.argument('output', type=click.File('wb')) def inout(input, output):while True:chunk = input.read(1024)if not chunk:break output.write(chunk)

運(yùn)行程序,先將文本寫進(jìn)文件,再讀取

如果參數(shù)值只是想做為文件名而已呢,很簡(jiǎn)單,將 type 指定為 click.Path():

@click.command() @click.argument('f', type=click.Path(exists=True)) def touch(f): click.echo(click.format_filename(f))
  • 打包跨平臺(tái)可執(zhí)行程序

通過click編寫了簡(jiǎn)單的命令行方法后,還需要把.py文件轉(zhuǎn)換成可以在控制臺(tái)里運(yùn)行的命令行程序。最簡(jiǎn)單的方法就是加上如下代碼:

if __name__ == '__main__':command()

click支持使用setuptools來更好的實(shí)現(xiàn)命令行程序打包,把源碼文件打包成系統(tǒng)中的可執(zhí)行程序,并且不限平臺(tái)。一般可通過在源碼根目錄下創(chuàng)建setup.py腳本,下面是一段簡(jiǎn)單的打包代碼:

from setuptools import setup setup(name='hello',version='0.1',py_modules=['hello'],install_requires=['click',],entry_points='''[console_scripts]hello=hello:cli''', )

留意entry_points字段,在console_scripts下,每一行都是一個(gè)控制臺(tái)腳本,等號(hào)左邊的是腳本的名稱,右邊的是click命令的導(dǎo)入路徑。

總結(jié)

以上是生活随笔為你收集整理的python Click库知识点汇总的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。