最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

python添加命令行參數(shù)的詳細過程

 更新時間:2023年06月09日 09:17:06   作者:Scoful  
Click 是 Flask 的開發(fā)團隊 Pallets 的另一款開源項目,它是用于快速創(chuàng)建命令行的第三方模塊,這篇文章主要介紹了python怎么添加命令行參數(shù),需要的朋友可以參考下

1. 安裝click

Click 是 Flask 的開發(fā)團隊 Pallets 的另一款開源項目,它是用于快速創(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 有兩個參數(shù):count 和 name,它們的值從命令行中獲取。

  • @click.command() 使函數(shù) hello 成為命令行接口;
  • @click.option 的第一個參數(shù)指定了命令行選項的名稱,可以看到,count 的默認值是 1;
  • 使用 click.echo 進行輸出是為了獲得更好的兼容性,因為 print 在 Python2 和 Python3 的用法有些差別。
調(diào)用結果1:
> python hello.py
> Your name: Scoful    # 這里會顯示 'Your name: '(對應代碼中的 prompt),接受用戶輸入
> Hello Scoful!
調(diào)用結果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)用結果3:
# 指定 count 和 name 的值
> python hello.py --count 3 --name Scoful    
> Hello Scoful!
> Hello Scoful!
> Hello Scoful!
調(diào)用結果4:
# 也可以使用 `=`,和上面等價
> python hello.py --count=3 --name=Scoful    
> Hello Scoful!
> Hello Scoful!
> Hello Scoful!
調(diào)用結果5:
# 沒有指定 count,默認值是 1
> python hello.py --name=Scoful              
> Hello Scoful!

3. 使用Group實現(xiàn)命令選擇

Click 通過 group 來創(chuàng)建一個命令行組,也就是說它可以有各種參數(shù)來解決相同類別的不同問題
使用group,加入2個命令,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,兩個命令列出來了
> 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行詳細配置

option 最基本的用法就是通過指定命令行選項的名稱,從命令行讀取參數(shù)值,再將其傳遞給函數(shù)。
常用的設置參數(shù)如下:

  • default: 設置命令行參數(shù)的默認值
  • help: 參數(shù)說明
  • type: 參數(shù)類型,可以是 string, int, float 等
  • prompt: 當在命令行中沒有輸入相應的參數(shù)時,會根據(jù) prompt 提示用戶輸入
  • nargs: 指定命令行參數(shù)接收的值的個數(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限定可選值

在某些情況下,一個參數(shù)的值只能是某些可選的值,如果用戶輸入了其他值,我們應該提示用戶輸入正確的值。

在這種情況下,我們可以通過 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.
# 故意選擇錯誤
> 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ù),當輸入的數(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ù)接收的值的個數(shù)

import click
@click.command()
@click.option('--center', type=float, help='center of the circle', nargs=2)  # 指定 center 是float類型,有且只能傳2個參數(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ù)個數(shù)
> python click_multi_values.py --center 3 4 --radius 10
> center: (3.0, 4.0), radius: 10.0
# 不正確的參數(shù)個數(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 提供了兩個參數(shù)來設置密碼的輸入:hide_input 和 confirmation_promt,其中,hide_input 用于隱藏輸入,confirmation_promt 用于重復輸入。

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:          # 重復一遍
> 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 表明該命令行選項優(yōu)先級高于其他選項;
  • expose_value=False 表示如果沒有輸入該命令行選項,會執(zhí)行既定的命令行流程;
  • callback 指定了輸入該命令行選項時,要跳轉執(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 選項
> Version 1.0

5. 使用argument

我們除了使用 @click.option 來添加可選參數(shù),還會經(jīng)常使用 @click.argument 來添加固定參數(shù)。

它的使用和 option 類似,但支持的功能比 option 少。

5.1 argument基礎用法

import click
@click.command()
@click.argument('coordinates')
def show(coordinates):
    click.echo('coordinates: %s' % coordinates)
if __name__ == '__main__':
    show()
# 錯誤,缺少參數(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.
# 錯誤用法,這是 option 參數(shù)的用法
> python click_argument.py --coordinates 10    
> Error: no such option: --coordinates
# 正確,直接輸入值即可
> python click_argument.py 10                  
> coordinates: 10

5.2 多個 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 個參數(shù)值,上面的例子中,dst 接收一個參數(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ù)對文件進行操作,click.File() 裝飾器就是處理這種操作的,尤其是在類 Unix 系統(tǒng)下,它支持以 - 符號作為標準輸入/輸出

# 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 進行輸出,如果配合 colorama 這個模塊,我們可以使用 click.secho 進行彩色輸出,在使用之前,使用 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ū)別

  • 需要提示補全輸入的時候使用 option()
  • 標志位(flag or acts) 使用 option()
  • option的值可以從環(huán)境變量獲取,而argument不行
  • option的值會在幫助里面列出,而argument不能

9. 增加-h的能力

默認情況下click不提供-h。需要使用context_settings參數(shù)來重寫默認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. 一個綜合的例子

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. 再一個綜合的例子

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!

到此這篇關于python添加命令行參數(shù)的文章就介紹到這了,更多相關python命令行參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • python中字典元素的創(chuàng)建、獲取和遍歷等字典知識點

    python中字典元素的創(chuàng)建、獲取和遍歷等字典知識點

    本文介紹了Python中的字典操作,包括字典的創(chuàng)建、元素獲取(使用鍵和get()方法)、刪除與清空(del和clear())、增加新鍵值對、修改已有值、獲取鍵、值和鍵值對以及遍歷字典的方法,同時闡述了字典的特點,如鍵的唯一性和無序性,以及字典生成式的使用
    2024-11-11
  • jupyter notebook運行代碼沒反應且in[ ]沒有*

    jupyter notebook運行代碼沒反應且in[ ]沒有*

    本文主要介紹了jupyter notebook運行代碼沒反應且in[ ]沒有*,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2022-03-03
  • 基于Python開發(fā)一個文件頭簽名分析工具

    基于Python開發(fā)一個文件頭簽名分析工具

    本文介紹了一個功能強大的文件頭簽名分析工具的實現(xiàn)原理和開發(fā)過程,該工具通過讀取文件頭部二進制簽名來識別文件真實類型,即使用戶修改了文件擴展名也能準確判斷,文章詳細解析了核心算法、GUI設計以及技術實現(xiàn)細節(jié),為開發(fā)類似工具提供了完整參考,需要的朋友可以參考下
    2025-05-05
  • python黑魔法之參數(shù)傳遞

    python黑魔法之參數(shù)傳遞

    這篇文章主要介紹了python黑魔法之參數(shù)傳遞,分析了python參數(shù)傳遞的方法,感興趣的小伙伴們可以參考一下
    2016-02-02
  • Python讀取pdf、word、excel、ppt、csv和txt文件提取所有文本

    Python讀取pdf、word、excel、ppt、csv和txt文件提取所有文本

    這篇文章主要給大家介紹了關于Python讀取pdf、word、excel、ppt、csv和txt文件提取所有文本的相關資料,文中通過代碼示例將實現(xiàn)的方法介紹的非常詳細,需要的朋友可以參考下
    2023-08-08
  • Python使用剪切板的方法

    Python使用剪切板的方法

    這篇文章主要為大家詳細介紹了Python使用剪切板的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-06-06
  • python讀取ini配置的類封裝代碼實例

    python讀取ini配置的類封裝代碼實例

    這篇文章主要介紹了python讀取ini配置的類封裝代碼實例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-01-01
  • Python獲取request response body的方法

    Python獲取request response body的方法

    本文介紹了使用Python的requests庫發(fā)送HTTP GET請求并獲取響應體的方法,同時,還簡要介紹了如何使用Flask框架在Python中創(chuàng)建一個簡單的網(wǎng)站,感興趣的朋友跟隨小編一起看看吧
    2024-11-11
  • 淺談Python中copy()方法的使用

    淺談Python中copy()方法的使用

    這篇文章主要介紹了淺談Python中copy()方法的使用,Python中的拷貝分為潛拷貝和深拷貝,本文只是簡單介紹用法,需要的朋友可以參考下
    2015-05-05
  • Python操作Spark常用命令指南

    Python操作Spark常用命令指南

    Python操作Spark的常用命令指南,涵蓋從環(huán)境配置到數(shù)據(jù)分析的核心操作,本文介紹了如何使用PySpark進行環(huán)境配置和核心操作,包括數(shù)據(jù)讀寫、處理與轉換、聚合與高級分析,以及運行SQL查詢和性能優(yōu)化,感興趣的朋友跟隨小編一起看看吧
    2026-02-02

最新評論

樟树市| 长岭县| 江源县| 博爱县| 都兰县| 长春市| 秭归县| 晋中市| 德阳市| 镇坪县| 将乐县| 内黄县| 交城县| 襄樊市| 西畴县| 临武县| 广灵县| 柳林县| 望奎县| 井研县| 汝城县| 黑龙江省| 巴彦淖尔市| 珲春市| 屯留县| 镇康县| 陵川县| 定边县| 阿拉善左旗| 罗源县| 屯昌县| 读书| 奉贤区| 蓝山县| 环江| 抚宁县| 鄂托克前旗| 桦川县| 繁昌县| 星子县| 绍兴县|