# 五分钟搞定python click包 **Repository Path**: zhpengfei/python-click ## Basic Information - **Project Name**: 五分钟搞定python click包 - **Description**: Python Click包的主要用法 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-03-04 - **Last Updated**: 2023-10-12 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README Python Click包的基本用法 # 基本用法 ## 基本概念 创建一个最简单的命令行脚本 ```python import click @click.command() def hello(): click.echo('Hello World!') if __name__ == '__main__': hello() ``` 脚本执行 ```shell $ python hello.py Hello World! ``` ## 创建子命令 第一种方法创建子命令 ```python @click.group() def cli(): pass @click.command() def initdb(): click.echo('Initialized the database') @click.command() def dropdb(): click.echo('Dropped the database') cli.add_command(initdb) cli.add_command(dropdb) ``` 第二种方法创建子命令 ```python @click.group() def cli(): pass @cli.command() def initdb(): click.echo('Initialized the database') @cli.command() def dropdb(): click.echo('Dropped the database') ``` ## 增加参数 增加参数有两种方法:option() 和 argument() ```python @click.command() @click.option('--count', default=1, help='number of greetings') @click.argument('name') def hello(count, name): for x in range(count): click.echo(f"Hello {name}!") ``` 脚本执行 ```shell $ python hello.py --help Usage: hello.py [OPTIONS] NAME Options: --count INTEGER number of greetings --help Show this message and exit. ``` # Setuptools基本使用 ## 基本案例 py脚本: ```python import click @click.command() def cli(): """Example script.""" click.echo('Hello World!') ``` setup.py ```python from setuptools import setup setup( name='yourscript', version='0.1.0', py_modules=['yourscript'], install_requires=[ 'Click', ], entry_points={ 'console_scripts': [ 'mycli = yourscript:cli', # 此处需要注意的是 等号前是命令的名称。 ], }, ) ``` 安装 ```shell virtualenv venv . venv/bin/activate pip install --editable . ``` 运行 ```shell $ mycli Hello World! ``` # 以options作为参数设定 ## 给参数命名 > 当一个参数有多个入口时该如何定义参数?例如 ``@click.option('-s', '--string-to-echo')``,这是函数应该以什么作为参数名呢? 主要规则如下: - "-f", "--foo-bar", the name is foo_bar - "-x", the name is x - "-f", "--filename", "dest", the name is dest - "--CamelCase", the name is camelcase - "-f", "-fb", the name is f - "--f", "--foo-bar", the name is f - "---f", the name is _f > 变量名不可使用python的保留关键字。``@click.option('--from', '-f', 'from_') `` ## 参数基本选项 如何给参数设置为必填、默认值、类型 ```python @click.option('--n', required=True, type=int, default=1,show_default=True) ``` > show_default的作用是在打印help信息是显示默认值 ```shell $ dots --help Usage: dots [OPTIONS] Options: --n INTEGER [default: 1] --help Show this message and exit. ``` 当参数的默认值是False时,在打印help信息时,不显示默认值 ```python @click.command() @click.option('--n', default=1, show_default=True) @click.option("--gr", is_flag=True, show_default=True, default=False, help="Greet the world.") @click.option("--br", is_flag=True, show_default=True, default=True, help="Add a thematic break") def dots(n, gr, br): if gr: click.echo('Hello world!') click.echo('.' * n) if br: click.echo('-' * n) ``` ```shell $ dots --help Usage: dots [OPTIONS] Options: --n INTEGER [default: 1] --gr Greet the world. --br Add a thematic break [default: True] --help Show this message and exit. ``` ## 多值参数 如果一个参数需要多个值,可以用nargs来设定值得个数 ```python @click.command() @click.option('--pos', nargs=2, type=float) def findme(pos): a, b = pos click.echo(f"{a} / {b}") ``` 给多值参数指定类型 ```python @click.command() @click.option('--item', nargs=4, type=click.Tuple([str, int, str, int])) def putitem(item): name, id, cpu, mem = item click.echo(f"name={name} id={id} cpu={cpu} mem={mem}") ``` 执行结果: ```shell $ python3 click_demo.py --item zpf 3 16 1024 name=zpf id=3 cpu=16 mem=1024 ``` ## 重复参数 如果一个参数需要用到多次,可以使用multiple=True选项 ```python @click.command() @click.option('--message', '-m', multiple=True) def commit(message): click.echo('\n'.join(message)) ``` 执行 ```shell $ commit -m foo -m bar foo bar ``` ## 计数参数