Python语言学习:click 包,开发自己的命令行
一个很好用的 python 开发命令行工具包
官方介绍
Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It’s the “Command Line Interface Creation Kit”. It’s highly configurable but comes with sensible defaults out of the box.
我的理解
- 一个
python
的包,可以用来创建 “beautiful command line interfaces” - 你只要写一些必须的代码即可完成
- 你可以叫他:
cli
创建工具(Command Line Interface Creation Kit).
安装
pip install click -U
先看一下 hello.py
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(f"Hello {name}!")
if __name__ == '__main__':
hello()
运行一下结果/帮助信息
$ py hello.py --count=3
Your name: aric
Hello aric!
Hello aric!
Hello aric!
$ python app.py --help
Usage: app.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.
让你的命令行可以本地运行
- 先添加一个 setup.py
- 构建 venv(虚拟环境)
- 本地安装
添加一个 setup.py
注意这一行
myhello=hello:cli
这里指定 的是运行的命令,以及真实的脚本程序对应的方法。
from setuptools import setup
setup(
name="myhello",
version='0.1',
py_modules=['hello'],
install_requires=[
'Click',
],
entry_points='''
[console_scripts]
myhello=hello:cli
''',
)
初始化 venv+pip
安装
$ python3 -m venv env
$ source env/bin/activate
$ python3 -m pip install --editable .
Obtaining file:///home/kdas/code/practice/yoclick
Collecting Click (from myhello==0.1)
Using cached click-6.7-py2.py3-none-any.whl
Installing collected packages: Click, myhello
Running setup.py develop for myhello
Successfully installed Click-6.7 myhello
$ myhello
Hello World