美文网首页
click模块用法

click模块用法

作者: 吕阳 | 来源:发表于2018-06-05 13:56 被阅读31次
    • click 模块用法.就是代替命令行.
    import click
    
    @click.command()
    @click.option('--count', default=2, 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()
    
    • 参考运行结果.
    $ python hello.py
    Your name: Ethan           # 这里会显示 'Your name: '(对应代码中的 prompt),接受用户输入
    Hello Ethan!
    
    $ python hello.py --help   # click 帮我们自动生成了 `--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.
    
    $ python hello.py --count 3 --name Ethan    # 指定 count 和 name 的值
    Hello Ethan!
    Hello Ethan!
    Hello Ethan!
    
    $ python hello.py --count=3 --name=Ethan    # 也可以使用 `=`,和上面等价
    Hello Ethan!
    Hello Ethan!
    Hello Ethan!
    
    $ python hello.py --name=Ethan              # 没有指定 count,默认值是 1
    Hello Ethan!
    
    • prompt='Your name', 这个会在命令行提示输入.

    • 嵌套的命令

    # 管理数据库的两种命令
    
    
    @click.group()
    def cli():
        pass
    
    
    @click.command()
    def initdb():
        click.echo('Initialized the database')
    
    
    @click.command()
    def dropdb():
        click.echo('drop the database')
    
    cli.add_command(initdb)
    cli.add_command(dropdb)
    
    • group装饰器的工作方式与command的是一样的,只不过可以集成多个命令。
      另外的一种写法
    @click.group()
    def cli():
        pass
    
    
    @cli.command()
    def initdb():
        click.echo('Initialized the database')
    
    
    @cli.command()
    def dropdb():
        click.echo('dropped the database')
    

    相关文章

      网友评论

          本文标题:click模块用法

          本文链接:https://www.haomeiwen.com/subject/eskpsftx.html