quickstart.rst
This file
Path
docs/quickstart.rst
112 lines · 2.5 KiB
Last changed by
Make documentation invoke click and fix a bunch of issuesArmin Ronacherbefore adoption0a44670
History of this fileTake it
1Quickstart2==========34.. currentmodule:: click56You can get the library directly from PyPI::78 pip install click910Basic Concepts11--------------1213Click is based on declaring commands through decorators. Internally there14is a non-decorator interface for advanced use cases but it's discouraged15for high-level usage.1617A function becomes a click command line tool by decorating it through18:func:`click.command`. In the most simple version just decorating a19function with this decorator will make it into a callable script:2021.. click:example::2223 import click2425 @click.command()26 def hello():27 print('Hello World!')2829What's happening is that the decorator converts the function into a30:class:`Command` which then can be invoked::3132 if __name__ == '__main__':33 hello()3435And what it looks like:3637.. click:run::3839 invoke(hello, args=[])4041And the corresponding help page:4243.. click:run::4445 invoke(hello, args=['--help'])4647Nesting Commands48----------------4950Commands can be attached to other commands of type :class:`Group`. This51allows arbitrary nesting of scripts. As an example here is a script that52implements two commands for managing databases:5354.. click:example::5556 @click.group()57 def cli():58 pass5960 @click.command()61 def initdb():62 print('Initialized the database')6364 @click.command()65 def dropdb():66 print('Dropped the database')6768 cli.add_command(initdb)69 cli.add_command(dropdb)7071As you can see the :func:`group` decorator works like the :func:`command`72decorator but creates a :class:`Group` object instead which can be given73multiple subcommands that can be attached with74:meth:`Group.add_command`.7576For simple scripts it's also possible to automatically attach and create a77command by using the :meth:`Group.command` decorator instead. The above78script can be written like this then:7980.. click:example::8182 @click.group()83 def cli():84 pass8586 @cli.command()87 def initdb():88 print('Initialized the database')8990 @cli.command()91 def dropdb():92 print('Dropped the database')9394Adding Parameters95-----------------9697To add parameters the :func:`option` and :func:`argument` decorators:9899.. click:example::100101 @click.command()102 @click.option('--count', default=1, help='number of greetings')103 @click.argument('name')104 def hello(count, name):105 for x in range(count):106 print('Hello %s!' % name)107108What it looks like:109110.. click:run::111112 invoke(hello, args=['--help'])