官网
Python 经常需要封装命令行,来达到执行指定函数的目的。常用的有 sys
, click , argparse。 sys 是 python 系统自带,使用起来不是很方便。所以一般都是用 click , argparse。
click 相较于 argparse代码更少,也更加简洁、直观。
安装
初级示例
创建一个 click_demo.py
1 2 3 4 5 6 7 8
| import click
@click.command() def main(): print("hello click")
if __name__ == '__main__': main()
|
运行
1 2 3
| python click_demo.py
hello click
|
中级示例
本示例中给函数添加参数,创建一个 click_demo.py
1 2 3 4 5 6 7 8 9 10
| import click
@click.command() @click.option("-n", "--name", help="your name") @click.option("-h", "--height", help="your height") def main(name, height): print("hello {} , {} is your height.".format(name, height))
if __name__ == '__main__': main()
|
运行
1 2 3
| python click_demo.py -n ABC -h 178
hello ABC , 178 is your height
|
option 装饰器说明
Options: 是一行一个参数,一个参数分为-开头的缩略参数,和–开头的完整参数名。
1 2 3 4 5 6 7 8 9 10 11 12
|
@click.command() @click.option("-n", "--name", type=str, required=True, help="your name") @click.option("-h", "--height", type=int, required=True, help="your height") def main(name, height): print("hello {} , {} is your height.".format(name, str(height)))
|
高级示例
本示例中添加多个命令行,创建一个 click_demo.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| import click
@click.group() def main(): print("main")
@click.command(name='add') @click.option("-n", "--name",required=True, help="your name") @click.option("-p", "--pwd", required=True, help="your password") def add_user(name, height): print("add user {} success".format(name))
@click.command(name='del') @click.option("-n", "--name",required=True, help="your name") def delete_user(name): print("delete user {} success".format(name))
if __name__ == '__main__': main.add_command(add_user) main.add_command(delete_user) main()
|
运行
1 2 3 4 5 6 7
| python click_demo.py add -n ABC -p 123456
add user ABC success
python click_demo.py del -n ABC
delete user ABC success
|