Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

163 lines · 4.7 KiB

Last changed by

Merge pull request #153 from iKevinY/click-renameArmin Ronacherbefore adoption327cfde

History of this file

Take it

1Quickstart2==========34.. currentmodule:: click56You can get the library directly from PyPI::78    pip install click910Screencast and Examples11-----------------------1213There is a screencast available which shows the basic API of Click and14how to build simple applications with it.  It also explores how to build15commands with subcommands.1617*   `Building Command Line Applications with Click18    <https://www.youtube.com/watch?v=kNke39OZ2k0>`_1920Examples of Click applications can be found in the documentation as well21as in the GitHub repository together with readme files:2223*   ``inout``: `File input and output24    <https://github.com/mitsuhiko/click/tree/master/examples/inout>`_25*   ``naval``: `Port of docopt naval example26    <https://github.com/mitsuhiko/click/tree/master/examples/naval>`_27*   ``aliases``: `Command alias example28    <https://github.com/mitsuhiko/click/tree/master/examples/aliases>`_29*   ``repo``: `Git-/Mercurial-like command line interface30    <https://github.com/mitsuhiko/click/tree/master/examples/repo>`_31*   ``complex``: `Complex example with plugin loading32    <https://github.com/mitsuhiko/click/tree/master/examples/complex>`_33*   ``validation``: `Custom parameter validation example34    <https://github.com/mitsuhiko/click/tree/master/examples/validation>`_35*   ``colors``: `Colorama ANSI color support36    <https://github.com/mitsuhiko/click/tree/master/examples/colors>`_37*   ``termui``: `Terminal UI functions demo38    <https://github.com/mitsuhiko/click/tree/master/examples/termui>`_3940Basic Concepts41--------------4243Click is based on declaring commands through decorators.  Internally, there44is a non-decorator interface for advanced use cases, but it's discouraged45for high-level usage.4647A function becomes a Click command line tool by decorating it through48:func:`click.command`.  At its simplest, just decorating a function49with this decorator will make it into a callable script:5051.. click:example::5253    import click5455    @click.command()56    def hello():57        click.echo('Hello World!')5859What's happening is that the decorator converts the function into a60:class:`Command` which then can be invoked::6162    if __name__ == '__main__':63        hello()6465And what it looks like:6667.. click:run::6869    invoke(hello, args=[])7071And the corresponding help page:7273.. click:run::7475    invoke(hello, args=['--help'])7677Echoing78-------7980Why does this example use :func:`echo` instead of the regular81:func:`print` function?  The answer to this question is that Click82attempts to support both Python 2 and Python 3 the same way and to be very83robust even when the environment is misconfigured.  Click wants to be84functional at least on a basic level even if everything is completely85broken.8687What this means is that the :func:`echo` function applies some error88correction in case the terminal is misconfigured instead of dying with an89:exc:`UnicodeError`.9091As an added benefit, starting with Click 2.0, the echo function also92has good support for ANSI colors.  It will automatically strip ANSI codes93if the output stream is a file and if colorama is supported, ANSI colors94will also work on Windows.  See :ref:`ansi-colors` for more information.9596If you don't need this, you can also use the `print()` construct /97function.9899Nesting Commands100----------------101102Commands can be attached to other commands of type :class:`Group`.  This103allows arbitrary nesting of scripts.  As an example here is a script that104implements two commands for managing databases:105106.. click:example::107108    @click.group()109    def cli():110        pass111112    @click.command()113    def initdb():114        click.echo('Initialized the database')115116    @click.command()117    def dropdb():118        click.echo('Dropped the database')119120    cli.add_command(initdb)121    cli.add_command(dropdb)122123As you can see, the :func:`group` decorator works like the :func:`command`124decorator, but creates a :class:`Group` object instead which can be given125multiple subcommands that can be attached with :meth:`Group.add_command`.126127For simple scripts, it's also possible to automatically attach and create a128command by using the :meth:`Group.command` decorator instead.  The above129script can instead be written like this:130131.. click:example::132133    @click.group()134    def cli():135        pass136137    @cli.command()138    def initdb():139        click.echo('Initialized the database')140141    @cli.command()142    def dropdb():143        click.echo('Dropped the database')144145Adding Parameters146-----------------147148To add parameters, use the :func:`option` and :func:`argument` decorators:149150.. click:example::151152    @click.command()153    @click.option('--count', default=1, help='number of greetings')154    @click.argument('name')155    def hello(count, name):156        for x in range(count):157            click.echo('Hello %s!' % name)158159What it looks like:160161.. click:run::162163    invoke(hello, args=['--help'])