python添加命令行參數(shù)的詳細(xì)過程
1. 安裝click
Click 是 Flask 的開發(fā)團(tuán)隊(duì) Pallets 的另一款開源項(xiàng)目,它是用于快速創(chuàng)建命令行的第三方模塊。官網(wǎng)文檔地址
pip install click
2. 官方例子,快速入門
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()
在上面的例子中,函數(shù) hello 有兩個(gè)參數(shù):count 和 name,它們的值從命令行中獲取。
- @click.command() 使函數(shù) hello 成為命令行接口;
- @click.option 的第一個(gè)參數(shù)指定了命令行選項(xiàng)的名稱,可以看到,count 的默認(rèn)值是 1;
- 使用 click.echo 進(jìn)行輸出是為了獲得更好的兼容性,因?yàn)?print 在 Python2 和 Python3 的用法有些差別。
調(diào)用結(jié)果1: > python hello.py > Your name: Scoful # 這里會顯示 'Your name: '(對應(yīng)代碼中的 prompt),接受用戶輸入 > Hello Scoful!
調(diào)用結(jié)果2: # click 幫我們自動生成了 `--help` 用法 > python 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.
調(diào)用結(jié)果3: # 指定 count 和 name 的值 > python hello.py --count 3 --name Scoful > Hello Scoful! > Hello Scoful! > Hello Scoful!
調(diào)用結(jié)果4: # 也可以使用 `=`,和上面等價(jià) > python hello.py --count=3 --name=Scoful > Hello Scoful! > Hello Scoful! > Hello Scoful!
調(diào)用結(jié)果5: # 沒有指定 count,默認(rèn)值是 1 > python hello.py --name=Scoful > Hello Scoful!
3. 使用Group實(shí)現(xiàn)命令選擇
Click 通過 group 來創(chuàng)建一個(gè)命令行組,也就是說它可以有各種參數(shù)來解決相同類別的不同問題
使用group,加入2個(gè)命令,initdb和dropdb
import click @click.group() def cli(): pass @click.command() def initdb(): click.echo('Initialized the database') ···· @click.command() def dropdb(): click.echo('Droped the database') cli.add_command(initdb) cli.add_command(dropdb) if __name__ == "__main__": cli()
# 查看help,兩個(gè)命令列出來了 > python hello.py > Usage: hello.py [OPTIONS] COMMAND [ARGS]... Options: --help Show this message and exit. Commands: dropdb initdb
# 指定命令initdb調(diào)用 > python hello.py initdb > Initialized the database
# 指定命令dropdb調(diào)用 > python hello.py dropdb > Droped the database
4. 使用click.option對指定命令的入?yún)⑦M(jìn)行詳細(xì)配置
option 最基本的用法就是通過指定命令行選項(xiàng)的名稱,從命令行讀取參數(shù)值,再將其傳遞給函數(shù)。
常用的設(shè)置參數(shù)如下:
- default: 設(shè)置命令行參數(shù)的默認(rèn)值
- help: 參數(shù)說明
- type: 參數(shù)類型,可以是 string, int, float 等
- prompt: 當(dāng)在命令行中沒有輸入相應(yīng)的參數(shù)時(shí),會根據(jù) prompt 提示用戶輸入
- nargs: 指定命令行參數(shù)接收的值的個(gè)數(shù)
- metavar:如何在幫助頁面表示值
4.1 指定 type
4.1.1 指定type是某種數(shù)據(jù)類型
import click @click.command() @click.option('--rate', type=float, help='rate') # 指定 rate 是 float 類型 def show(rate): click.echo('rate: %s' % rate) if __name__ == '__main__': show()
# 查看help > python click_type.py --help > Usage: click_type.py [OPTIONS] Options: --rate FLOAT rate --help Show this message and exit.
> python click_type.py --rate 1 > rate: 1.0
> python click_type.py --rate 0.66 > rate: 0.66
4.1.2 指定type限定可選值
在某些情況下,一個(gè)參數(shù)的值只能是某些可選的值,如果用戶輸入了其他值,我們應(yīng)該提示用戶輸入正確的值。
在這種情況下,我們可以通過 click.Choice() 來限定
import click @click.command() @click.option('--gender', type=click.Choice(['man', 'woman']), help='gender') # 指定 gender 只能選 man 或 woman def show(gender): click.echo('gender: %s' % gender) if __name__ == '__main__': show()
# 查看help > python click_choice.py --help > Usage: click_choice.py [OPTIONS] Options: --gender [man|woman] --help Show this message and exit.
# 故意選擇錯(cuò)誤 > python click_choice.py --gender boy > Usage: click_choice.py [OPTIONS] Error: Invalid value for "--gender": invalid choice: boy. (choose from man, woman)
# 選擇正確 > python click_choice.py --gender man > gender: man
4.1.3 指定type限定參數(shù)的范圍
import click @click.command() @click.option('--count', type=click.IntRange(0, 20, clamp=True)) # count 只能輸入0-20之間的數(shù)據(jù),當(dāng)輸入的數(shù)據(jù)不在區(qū)間內(nèi),就直接選20 @click.option('--digit', type=click.IntRange(0, 10)) # digit 只能輸入0-10之間的數(shù)據(jù) def repeat(count, digit): click.echo(str(digit) * count) if __name__ == '__main__': repeat()
# 故意輸入大于20的 > python click_repeat.py --count=1000 --digit=5 > 55555555555555555555
# 故意輸入大于10的 > python click_repeat.py --count=1000 --digit=12 > Usage: repeat [OPTIONS] Error: Invalid value for "--digit": 12 is not in the valid range of 0 to 10.
4.2 指定命令行參數(shù)接收的值的個(gè)數(shù)
import click @click.command() @click.option('--center', type=float, help='center of the circle', nargs=2) # 指定 center 是float類型,有且只能傳2個(gè)參數(shù) @click.option('--radius', type=float, help='radius of the circle') # 指定 radius 是float類型 def show(center, radius): click.echo('center: %s, radius: %s' % (center, radius)) if __name__ == '__main__': show()
# 查看help > python click_multi_values.py --help > Usage: click_multi_values.py [OPTIONS] Options: --center FLOAT... center of the circle --radius FLOAT radius of the circle
# 正確的參數(shù)個(gè)數(shù) > python click_multi_values.py --center 3 4 --radius 10 > center: (3.0, 4.0), radius: 10.0
# 不正確的參數(shù)個(gè)數(shù) > python click_multi_values.py --center 3 4 5 --radius 10 > Usage: click_multi_values.py [OPTIONS] Error: Got unexpected extra argument (5)
4.3 輸入密碼隱藏顯示
方式1,option 提供了兩個(gè)參數(shù)來設(shè)置密碼的輸入:hide_input 和 confirmation_promt,其中,hide_input 用于隱藏輸入,confirmation_promt 用于重復(fù)輸入。
import click @click.command() @click.option('--password', prompt=True, hide_input=True, confirmation_prompt=True) def input_password(password): click.echo('password: %s' % password) if __name__ == '__main__': input_password()
> python click_password.py > Password: # 不會顯示密碼 > Repeat for confirmation: # 重復(fù)一遍 > password: 123
方式2,click 也提供了一種快捷的方式,通過使用 @click.password_option(),上面的代碼可以簡寫成:
import click @click.command() @click.password_option() def input_password(password): click.echo('password: %s' % password) if __name__ == '__main__': input_password()
4.4 使用回調(diào),指定優(yōu)先級
import click def print_version(ctx, param, value): if not value or ctx.resilient_parsing: return click.echo('Version 1.0') ctx.exit() @click.command() @click.option('--version', is_flag=True, callback=print_version, expose_value=False, is_eager=True) @click.option('--name', default='Ethan', help='name') def hello(name): click.echo('Hello %s!' % name) if __name__ == '__main__': hello()
- is_eager=True 表明該命令行選項(xiàng)優(yōu)先級高于其他選項(xiàng);
- expose_value=False 表示如果沒有輸入該命令行選項(xiàng),會執(zhí)行既定的命令行流程;
- callback 指定了輸入該命令行選項(xiàng)時(shí),要跳轉(zhuǎn)執(zhí)行的函數(shù)
- is_flag=True 表明參數(shù)值可以省略
> python click_eager.py > Hello Ethan!
> python click_eager.py --version # 攔截既定的命令行執(zhí)行流程 > Version 1.0
> python click_eager.py --name Michael > Hello Michael!
> python click_eager.py --version --name Ethan # 忽略 name 選項(xiàng) > Version 1.0
5. 使用argument
我們除了使用 @click.option 來添加可選參數(shù),還會經(jīng)常使用 @click.argument 來添加固定參數(shù)。
它的使用和 option 類似,但支持的功能比 option 少。
5.1 argument基礎(chǔ)用法
import click @click.command() @click.argument('coordinates') def show(coordinates): click.echo('coordinates: %s' % coordinates) if __name__ == '__main__': show()
# 錯(cuò)誤,缺少參數(shù) coordinates > python click_argument.py > Usage: click_argument.py [OPTIONS] COORDINATES Error: Missing argument "coordinates".
# argument 指定的參數(shù)在 help 中沒有顯示 > python click_argument.py --help > Usage: click_argument.py [OPTIONS] COORDINATES Options: --help Show this message and exit.
# 錯(cuò)誤用法,這是 option 參數(shù)的用法 > python click_argument.py --coordinates 10 > Error: no such option: --coordinates
# 正確,直接輸入值即可 > python click_argument.py 10 > coordinates: 10
5.2 多個(gè) argument
import click @click.command() @click.argument('x') @click.argument('y') @click.argument('z') def show(x, y, z): click.echo('x: %s, y: %s, z:%s' % (x, y, z)) if __name__ == '__main__': show()
> python click_argument.py 10 20 30 > x: 10, y: 20, z:30
> python click_argument.py 10 > Usage: click_argument.py [OPTIONS] X Y Z Error: Missing argument "y".
> python click_argument.py 10 20 > Usage: click_argument.py [OPTIONS] X Y Z Error: Missing argument "z".
> python click_argument.py 10 20 30 40 > Usage: click_argument.py [OPTIONS] X Y Z Error: Got unexpected extra argument (40)
5.3 不定argument參數(shù)
import click @click.command() @click.argument('src', nargs=-1) @click.argument('dst', nargs=1) def move(src, dst): click.echo('move %s to %s' % (src, dst)) if __name__ == '__main__': move()
其中,nargs=-1 表明參數(shù) src 接收不定量的參數(shù)值,參數(shù)值會以 tuple 的形式傳入函數(shù)。
如果 nargs 大于等于 1,表示接收 nargs 個(gè)參數(shù)值,上面的例子中,dst 接收一個(gè)參數(shù)值。
python click_argument.py file1 trash # src=('file1',) dst='trash' move ('file1',) to trash
python click_argument.py file1 file2 file3 trash # src=('file1', 'file2', 'file3') dst='trash' move ('file1', 'file2', 'file3') to trash
6. 參數(shù)是文件
Click 支持通過文件名參數(shù)對文件進(jìn)行操作,click.File() 裝飾器就是處理這種操作的,尤其是在類 Unix 系統(tǒng)下,它支持以 - 符號作為標(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)
7. 彩色輸出
在前面的例子中,我們使用 click.echo 進(jìn)行輸出,如果配合 colorama 這個(gè)模塊,我們可以使用 click.secho 進(jìn)行彩色輸出,在使用之前,使用 pip 安裝 colorama:pip install colorama
import click @click.command() @click.option('--name', help='The person to greet.') def hello(name): click.secho('Hello %s!' % name, fg='red', underline=True) click.secho('Hello %s!' % name, fg='yellow', bg='black') if __name__ == '__main__': hello()
- fg 表示前景顏色(即字體顏色),可選值有:BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE 等;
- bg 表示背景顏色,可選值有:BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE 等;
- underline 表示下劃線,可選的樣式還有:dim=True,bold=True 等;
python hello.py --name=scoful
8. option和option的區(qū)別
- 需要提示補(bǔ)全輸入的時(shí)候使用 option()
- 標(biāo)志位(flag or acts) 使用 option()
- option的值可以從環(huán)境變量獲取,而argument不行
- option的值會在幫助里面列出,而argument不能
9. 增加-h的能力
默認(rèn)情況下click不提供-h。需要使用context_settings參數(shù)來重寫默認(rèn)help_option_names。
import click CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.command(context_settings=CONTEXT_SETTINGS) @click.option('--name', help='The person to greet.') def hello(name): click.secho('Hello %s!' % name, fg='red', underline=True) click.secho('Hello %s!' % name, fg='yellow', bg='black') if __name__ == '__main__': hello()
> python hello.py --help > Usage: hellp.py [OPTIONS] Options: --name TEXT The person to greet. -h, --help Show this message and exit.
> python hello.py -h > Usage: hellp.py [OPTIONS] Options: --name TEXT The person to greet. -h, --help Show this message and exit.
10. 一個(gè)綜合的例子
import click CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) def greeter(**kwargs): output = '{0}, {1}!'.format(kwargs['greeting'], kwargs['name']) if kwargs['caps']: output = output.upper() print(output) @click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version='1.0.0') def greet(): pass @greet.command() @click.argument('name') @click.option('--greeting', default='Hello', help='word to use for the greeting') @click.option('--caps', is_flag=True, help='uppercase the output') def hello(**kwargs): greeter(**kwargs) @greet.command() @click.argument('name') @click.option('--greeting', default='Goodbye', help='word to use for the greeting') @click.option('--caps', is_flag=True, help='uppercase the output') def goodbye(**kwargs): greeter(**kwargs) @greet.command() @click.option('--hash-type', type=click.Choice(['md5', 'sha1'])) def digest(hash_type): click.echo(hash_type) if __name__ == '__main__': greet()
> python hello.py -h > Usage: hello.py [OPTIONS] COMMAND [ARGS]... Options: --version Show the version and exit. -h, --help Show this message and exit. Commands: digest goodbye hello Process finished with exit code 0
> python hello.py digest --hash-type=md5 > md5
> python hello.py goodbye scoful > Goodbye, scoful!
> python hello.py goodbye scoful --greeting=Halo > Halo, scoful!
> python hello.py goodbye scoful --greeting=Halo --caps > HALO, SCOFUL!
11. 再一個(gè)綜合的例子
import click CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help']) @click.group(context_settings=CONTEXT_SETTINGS) @click.version_option(version='1.0.0') def cli(): """ Repo is a command line tool that showcases how to build complex command line interfaces with Click. This tool is supposed to look like a distributed version control system to show how something like this can be structured. """ pass @cli.command() @click.argument('name', default='all', required=True) # @click.option('--greeting', default='Hello', help='word to use for the greeting') # @click.option('--caps', is_flag=True, help='uppercase the output') def hellocmd(name): click.echo(click.style('I am colored %s and bold' % name, fg='green', bold=True)) @cli.command() @click.option('-t', default='a', required=True, type=click.Choice(['a', 'h']), prompt=True, help='檢查磁盤空間,a表示所有空間,h表示空間大于50%') def dfcmd(t): """ 檢查磁盤空間 dfcmd :param t: :return: """ click.echo(click.style('檢查磁盤空間', fg='green', bold=True)) @cli.command(context_settings=CONTEXT_SETTINGS) @click.argument('x', type=int, required=True) def square(x): """ 得到x平方 square x """ click.echo(click.style('x= %s' % x, fg='green', bold=True)) print(x * x) if __name__ == '__main__': cli()
enjoy!
到此這篇關(guān)于python添加命令行參數(shù)的文章就介紹到這了,更多相關(guān)python命令行參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python基于雙向鏈表實(shí)現(xiàn)LFU算法
這篇文章主要為大家詳細(xì)介紹了python基于雙向鏈表實(shí)現(xiàn)LFU算法,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2022-05-05用python實(shí)現(xiàn)將數(shù)組元素按從小到大的順序排列方法
今天小編就為大家分享一篇用python實(shí)現(xiàn)將數(shù)組元素按從小到大的順序排列方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07Python生態(tài)圈圖像格式轉(zhuǎn)換問題(推薦)
在Python生態(tài)圈里,最常用的圖像庫是PIL——盡管已經(jīng)被后來的pillow取代,但因?yàn)閜illow的API幾乎完全繼承了PIL,所以大家還是約定俗成地稱其為PIL。這篇文章主要介紹了Python生態(tài)圈圖像格式轉(zhuǎn)換問題,需要的朋友可以參考下2019-12-12