Click: 命令行工具神器

Click是一個Python用來快速實現命令行應用程序的包,主要優點表如今如下三點:python

  • 任意嵌套命令
  • 自動生成幫助頁
  • 自動運行時lazy加載子命令

示例程序:函數

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

執行結果:this

$ python hello.py --count=3
Your name: John
Hello John!
Hello John!
Hello John!

它還會自動生成格式化好的幫助信息:編碼

$ 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.

快速入門

安裝

pip install Click

建立一個命令

經過裝時器函數click.command()來註冊命令命令行

import click


@click.command()
def hello():
    click.echo("Hello World!")

if __name__ == '__main__':
    hello()

輸出結果:code

$ python hello.py
Hello World!

相應的幫助頁:繼承

$ python hello.py --help
Usage: hello.py [OPTIONS]

Options:
  --help  Show this message and exit.

輸出

爲何不用print,還要加入一個echo呢。Click嘗試用一個兼容Python 2和Python 3相同方式來處理。也防止了一些終端編碼不一致出現UnicodeError異常。ip

Click 2.0還加入了ANSI colors支持,若是輸出結果到文件中還會自動去處ANSI codes。get

要使用ANSI colors咱們須要colorama包配合操做:it

pipenv install colorama

示例:
click.echo(click.style("Hello World!", fg='green')) # click.secho('Hello World!', fg='green')

嵌套命令

import click


@click.group()
def cli():
    pass

@cli.command()
def initdb():
    click.echo('Initialized the database')

@cli.command()
def dropdb():
    click.echo('Dropped the database')

if __name__ == '__main__':
    cli()

添加參數

使用option()和argument()裝飾器增長參數

@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('Hello %s!' % name)
What it looks like:

$ python hello.py --help
Usage: hello.py [OPTIONS] NAME

Options:
  --count INTEGER  number of greetings
  --help           Show this message and exit.

繼承setuptools

查看詳情

相關文章
相關標籤/搜索