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

暂时到这里

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,180评论 0 10
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 7,956评论 0 0
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,503评论 0 23
  • 在MongoDB中使用批量操作或块操作「Bulk Write」在效率上有非常大的提升,适合大量写操作 第一次尝试使...
    HughDong阅读 4,130评论 0 2
  • 为IOS模拟器生成GIF图片 安装GIF神器:GIF Brewery 3 安装成功后打开GIF Brewery 3...
    mocoe阅读 3,933评论 0 0

友情链接更多精彩内容