Python 的 Click 模块

Click

简介

Click 官方文档
argparse 模块相比,更直观,更直观,并且支持 nesting commands
类似于 git 那种,除了这个特性支持的比较好,没觉得简洁到哪里去⊙﹏⊙

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.

It aims to make the process of writing command line tools quick and fun while also preventing any frustration caused by the inability to implement an intended CLI API.

Click in three points:

  • arbitrary nesting of commands
  • automatic help page generation
  • supports lazy loading of subcommands at runtime

模块的使用

-h参数的支持(同@click.group通用)

CONTEXT_SETTINGS = dict(help_option_names=['-h', '--help'])

@click.command(context_settings=CONTEXT_SETTINGS)
def cli():
    pass

添加参数

argumentoption的区别

click supports two types of parameters for scripts: options and arguments. There is generally some confusion among authors of command line scripts of when to use which, so here is a quick overview of the differences. As its name indicates, an option is optional. While arguments can be optional within reason, they are much more restricted in how optional they can be.

To help you decide between options and arguments, the recommendation is to use arguments exclusively for things like going to subcommands or input filenames / URLs, and have everything else be an option instead.

添加argument(@click.argument)

# 我是真心不喜欢这种,没有办法添加help~限制又多
@click.argument('filename',
                type=click.File('r'))

添加option(@click.option)

@click.option('-f', '-fasta', 'file_name',
              type=click.File('r'),
              required=True,
              help=u'The fasta file input.')

添加密码参数

# 如果输入 -p 则传入其后的参数
# 如果没有输入 -p,则提示输入
@click.option('-p', '--password',
              prompt=True, hide_input=True,
              help='The password for email')

高亮显示

click.secho(
    '**** The failed files are stored at {} ****'.format(file_failed),
    fg='red')

暂时到这里

你可能感兴趣的:(Python 的 Click 模块)