click python cli 开发包

python click 包是一个方便的cli 开发包,我们可以用来开发强大的cli 应用

使用venv 进行环境准备,示例代码来自官方

venv 环境准备

python3 -m venv demoapp

安装

pip install click

基本使用

  • 代码

    cli.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 _ in range(count):
        click.echo("Hello, %s!" % name)

if __name__ == '__main__':
    hello()
  • 运行
python cli.py

效果

python cli.py 
Your name: dalong
Hello, dalong!

制作一个pip 包

制作pip 包可以方便进行我们的代码分发,还是使用venv 进行环境的准备

  • 项目结构
├── README.md
├── cli
│ └── __init__.py
└── setup.py
  • 代码说明
    cli/init.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 _ in range(count):
        click.echo("Hello, %s!" % name)

if __name__ == '__main__':
    hello()

setup.py pip 包配置

import setuptools
with open("README.md", "r") as fh:
    long_description = fh.read()

setuptools.setup(
    name="dalongrong_cli-demo",
    version="0.0.1",
    author="dalongrong",
    author_email="1141591465@qq.com",
    description="a simple cli project",
    long_description=long_description,
    install_requires=['click'],
    long_description_content_type="text/markdown",
    url="https://github.com/rongfengliang/click-cli-demo.git",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    entry_points={
        'console_scripts': [
            'dalongcli=cli:hello',
        ],
    }
)
  • 本地安装测试
pip install .

cli 使用命令

dalongcli --name dalong --count 3

效果

Hello, dalong!
Hello, dalong!
Hello, dalong!
  • 说明
    比较好的方法是push 到pip 私服(企业内部),或者push 到公共pip 仓库,方便大家都使用,具体的可以参考 自定义pip 开发

参考资料

https://github.com/pallets/click
https://click.palletsprojects.com/en/7.x/
https://www.cnblogs.com/rongfengliang/p/10219292.html
https://github.com/rongfengliang/click-cli-demo
https://packaging.python.org/guides/distributing-packages-using-setuptools/#install-requires

posted on 2019-04-22 11:02  荣锋亮  阅读(1490)  评论(0编辑  收藏  举报

导航