1.如何安装


  使用命令pip install click或者在PyCharm中安装


  2.隔离环境vitualenv


  linux或MAC上


  sudo pip install virtualenv


  windows


  pip install virtualenv


  43如何激活


  现在,每当您想要处理项目时,您只需激活相应的环境。在OS X和Linux上,执行以下操作:


  $ . venv/bin/activate


  如果您是Windows用户,则以下命令适合您:


  $ venv\scripts\activate


  退出激活


  $ deactivate


  输入以下命令以在virtualenv中激活Click:


  $ pip install Click


  4.click语法


  函数通过装饰来成为Click命令行工具 click.command()。最简单的方法是,使用这个装饰器装饰一个函数会使它成为一个可调用的脚本:


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


  根据参数格式执行


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


  6.打印函数click.echo


  使用echo()而不是常规 print()函数?这个问题的答案是Click尝试以相同的方式支持Python 2和Python 3


  从Click 2.0开始,echo函数也对ANSI颜色有很好的支持


  7.嵌套命令


  使用@click.group()实现命令的嵌套,即可以存在子命令


  @click.group()


  def cli():


  pass


  @click.command()


  def initdb():


  click.echo('Initialized the database')


  @click.command()


  def dropdb():


  click.echo('Dropped the database')


  cli.add_command(initdb)


  cli.add_command(dropdb)


  正如您所看到的,group()装饰器的工作方式与command() 装饰器类似,但创建了一个Group对象,可以为其提供多个可以附加的子命令Group.add_command()。


  对于简单脚本,也可以使用Group.command()装饰器自动附加和创建命令。上面的脚本可以这样编写:


  @click.group()


  def cli():


  pass


  @cli.command()


  def initdb():


  click.echo('Initialized the database')


  @cli.command()


  def dropdb():无锡人流多少钱 http://www.bhnnk120.com/


  click.echo('Dropped the database')


  然后,您将Group在setuptools入口点或其他调用中调用:


  if __name__ == '__main__':


  cli()


  8.增加参数


  添加参数@click.option要添加参数,请使用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)


  生成的帮助文档如下


  $ python hello.py --help


  Usage: hello.py [OPTIONS] NAME


  Options:


  --count INTEGER number of greetings


  --help Show this message and exit.


  生成的帮助文档如下


  $ python hello.py --help


  Usage: hello.py [OPTIONS] NAME


  Options:


  --count INTEGER number of greetings


  --help Show this message and exit.