python添加命令行参数的详细过程

作者:Scoful 时间:2022-03-18 15:34:27 

1. 安装click

Click 是 Flask 的开发团队 Pallets 的另一款开源项目,它是用于快速创建命令行的第三方模块。官网文档地址

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()

在上面的例子中,函数 hello 有两个参数:count 和 name,它们的值从命令行中获取。

  • @click.command() 使函数 hello 成为命令行接口;

  • @click.option 的第一个参数指定了命令行选项的名称,可以看到,count 的默认值是 1;

  • 使用 click.echo 进行输出是为了获得更好的兼容性,因为 print 在 Python2 和 Python3 的用法有些差别。

调用结果1:
> python hello.py
> Your name: Scoful    # 这里会显示 'Your name: '(对应代码中的 prompt),接受用户输入
> Hello Scoful!
调用结果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.
调用结果3:
# 指定 count 和 name 的值
> python hello.py --count 3 --name Scoful    
> Hello Scoful!
> Hello Scoful!
> Hello Scoful!
调用结果4:
# 也可以使用 `=`,和上面等价
> python hello.py --count=3 --name=Scoful    
> Hello Scoful!
> Hello Scoful!
> Hello Scoful!
调用结果5:
# 没有指定 count,默认值是 1
> python hello.py --name=Scoful              
> Hello Scoful!

3. 使用Group实现命令选择

Click 通过 group 来创建一个命令行组,也就是说它可以有各种参数来解决相同类别的不同问题
使用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调用
> python hello.py initdb
> Initialized the database
# 指定命令dropdb调用
> python hello.py dropdb
> Droped the database

4. 使用click.option对指定命令的入参进行详细配置

option 最基本的用法就是通过指定命令行选项的名称,从命令行读取参数值,再将其传递给函数。
常用的设置参数如下:

  • default: 设置命令行参数的默认值

  • help: 参数说明

  • type: 参数类型,可以是 string, int, float 等

  • prompt: 当在命令行中没有输入相应的参数时,会根据 prompt 提示用户输入

  • nargs: 指定命令行参数接收的值的个数

  • metavar:如何在帮助页面表示值

4.1 指定 type

4.1.1 指定type是某种数据类型

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限定可选值

在某些情况下,一个参数的值只能是某些可选的值,如果用户输入了其他值,我们应该提示用户输入正确的值。

在这种情况下,我们可以通过 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限定参数的范围

import click
@click.command()
@click.option('--count', type=click.IntRange(0, 20, clamp=True)) # count 只能输入0-20之间的数据,当输入的数据不在区间内,就直接选20
@click.option('--digit', type=click.IntRange(0, 10)) # digit 只能输入0-10之间的数据
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 指定命令行参数接收的值的个数

import click
@click.command()
@click.option('--center', type=float, help='center of the circle', nargs=2)  # 指定 center 是float类型,有且只能传2个参数
@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
# 正确的参数个数
> python click_multi_values.py --center 3 4 --radius 10
> center: (3.0, 4.0), radius: 10.0
# 不正确的参数个数
> 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 提供了两个参数来设置密码的输入: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 使用回调,指定优先级

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 表明该命令行选项优先级高于其他选项;

  • expose_value=False 表示如果没有输入该命令行选项,会执行既定的命令行流程;

  • callback 指定了输入该命令行选项时,要跳转执行的函数

  • is_flag=True 表明参数值可以省略

> python click_eager.py
> Hello Ethan!
> python click_eager.py --version                   # 拦截既定的命令行执行流程
> 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 来添加可选参数,还会经常使用 @click.argument 来添加固定参数。

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

5.1 argument基础用法

import click
@click.command()
@click.argument('coordinates')
def show(coordinates):
   click.echo('coordinates: %s' % coordinates)
if __name__ == '__main__':
   show()
# 错误,缺少参数 coordinates
> python click_argument.py                    
> Usage: click_argument.py [OPTIONS] COORDINATES
Error: Missing argument "coordinates".
# argument 指定的参数在 help 中没有显示
> python click_argument.py --help              
> Usage: click_argument.py [OPTIONS] COORDINATES
Options:
 --help  Show this message and exit.
# 错误用法,这是 option 参数的用法
> 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参数

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 表明参数 src 接收不定量的参数值,参数值会以 tuple 的形式传入函数。

如果 nargs 大于等于 1,表示接收 nargs 个参数值,上面的例子中,dst 接收一个参数值。

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. 参数是文件

Click 支持通过文件名参数对文件进行操作,click.File() 装饰器就是处理这种操作的,尤其是在类 Unix 系统下,它支持以 - 符号作为标准输入/输出

# 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

python添加命令行参数的详细过程

8. option和option的区别

  • 需要提示补全输入的时候使用 option()

  • 标志位(flag or acts) 使用 option()

  • option的值可以从环境变量获取,而argument不行

  • option的值会在帮助里面列出,而argument不能

9. 增加-h的能力

默认情况下click不提供-h。需要使用context_settings参数来重写默认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!

来源:https://blog.csdn.net/Scoful/article/details/131098540

标签:python,命令行,参数
0
投稿

猜你喜欢

  • 浅淡BANNER设计

    2010-09-25 18:37:00
  • PHP实战之投票系统的实现

    2023-10-24 10:40:39
  • 为什么str(float)在Python 3中比Python 2返回更多的数字

    2022-11-09 22:55:56
  • python实现中文文本分句的例子

    2023-02-15 12:16:24
  • Django多个app urls配置代码实例

    2021-11-23 10:01:13
  • 举例讲解Python中装饰器的用法

    2022-12-26 17:02:23
  • Python并行分布式框架Celery详解

    2023-06-23 10:05:21
  • python 中pyqt5 树节点点击实现多窗口切换问题

    2021-07-28 06:19:39
  • 浅谈用户注册表单

    2008-11-13 12:27:00
  • 在Oracle PL/SQL中游标声明中表名动态变化的方法

    2009-02-28 10:39:00
  • 5招优化MySQL插入方法

    2009-04-02 10:49:00
  • Python 3 使用Pillow生成漂亮的分形树图片

    2022-05-03 14:53:23
  • php简单获取复选框值的方法

    2023-11-15 20:57:28
  • 论坛首页效果图设计

    2009-03-19 13:46:00
  • python3 使用Opencv打开USB摄像头,配置1080P分辨率的操作

    2024-01-02 12:40:07
  • 分享2个方便调试Python代码的实用工具

    2021-08-26 18:50:08
  • python游戏实战项目之俄罗斯方块的魅力

    2021-12-07 19:38:23
  • Tensorflow中的降维函数tf.reduce_*使用总结

    2021-10-18 15:16:14
  • asp下实现代码的“运行代码”“复制代码”“保存代码”功能源码

    2011-04-14 10:39:00
  • 一些常用的Python爬虫技巧汇总

    2021-01-02 22:51:56
  • asp之家 网络编程 m.aspxhome.com