quickstart.rst
This file
Path
docs/quickstart.rst
210 lines · 6.9 KiB
Last changed by
Make examples docs nicer. (#2580)Rowlando13before adoption3ecc65b
History of this fileTake it
1Quickstart2==========34.. currentmodule:: click56Install7----------------------8Install from PyPI::910 pip install click1112Installing into a virtual environment is highly recommended. We suggest :ref:`virtualenv-heading`.1314Examples15-----------------------1617Some standalone examples of Click applications are packaged with Click. They are available in the `examples folder <https://github.com/pallets/click/tree/main/examples>`_ of the repo.1819* `inout <https://github.com/pallets/click/tree/main/examples/inout>`_ : A very simple example of an application that can read from files and write to files and also accept input from stdin or write to stdout.20* `validation <https://github.com/pallets/click/tree/main/examples/validation>`_ : A simple example of an application that performs custom validation of parameters in different ways.21* `naval <https://github.com/pallets/click/tree/main/examples/naval>`_ : Port of the `docopt <http://docopt.org/>`_ naval example.22* `colors <https://github.com/pallets/click/tree/main/examples/colors>`_ : A simple example that colorizes text. Uses colorama on Windows.23* `aliases <https://github.com/pallets/click/tree/main/examples/aliases>`_ : An advanced example that implements :ref:`aliases`.24* `imagepipe <https://github.com/pallets/click/tree/main/examples/imagepipe>`_ : A complex example that implements some :ref:`multi-command-chaining` . It chains together image processing instructions. Requires pillow.25* `repo <https://github.com/pallets/click/tree/main/examples/repo>`_ : An advanced example that implements a Git-/Mercurial-like command line interface.26* `complex <https://github.com/pallets/click/tree/main/examples/complex>`_ : A very advanced example that implements loading subcommands dynamically from a plugin folder.27* `termui <https://github.com/pallets/click/tree/main/examples/termui>`_ : A simple example that showcases terminal UI helpers provided by click.2829Basic Concepts - Creating a Command30-----------------------------------3132Click is based on declaring commands through decorators. Internally, there33is a non-decorator interface for advanced use cases, but it's discouraged34for high-level usage.3536A function becomes a Click command line tool by decorating it through37:func:`click.command`. At its simplest, just decorating a function38with this decorator will make it into a callable script:3940.. click:example::4142 import click4344 @click.command()45 def hello():46 click.echo('Hello World!')4748What's happening is that the decorator converts the function into a49:class:`Command` which then can be invoked::5051 if __name__ == '__main__':52 hello()5354And what it looks like:5556.. click:run::5758 invoke(hello, args=[], prog_name='python hello.py')5960And the corresponding help page:6162.. click:run::6364 invoke(hello, args=['--help'], prog_name='python hello.py')6566Echoing67-------6869Why does this example use :func:`echo` instead of the regular70:func:`print` function? The answer to this question is that Click71attempts to support different environments consistently and to be very72robust even when the environment is misconfigured. Click wants to be73functional at least on a basic level even if everything is completely74broken.7576What this means is that the :func:`echo` function applies some error77correction in case the terminal is misconfigured instead of dying with a78:exc:`UnicodeError`.7980The echo function also supports color and other styles in output. It81will automatically remove styles if the output stream is a file. On82Windows, colorama is automatically installed and used. See83:ref:`ansi-colors`.8485If you don't need this, you can also use the `print()` construct /86function.8788Nesting Commands89----------------9091Commands can be attached to other commands of type :class:`Group`. This92allows arbitrary nesting of scripts. As an example here is a script that93implements two commands for managing databases:9495.. click:example::9697 @click.group()98 def cli():99 pass100101 @click.command()102 def initdb():103 click.echo('Initialized the database')104105 @click.command()106 def dropdb():107 click.echo('Dropped the database')108109 cli.add_command(initdb)110 cli.add_command(dropdb)111112As you can see, the :func:`group` decorator works like the :func:`command`113decorator, but creates a :class:`Group` object instead which can be given114multiple subcommands that can be attached with :meth:`Group.add_command`.115116For simple scripts, it's also possible to automatically attach and create a117command by using the :meth:`Group.command` decorator instead. The above118script can instead be written like this:119120.. click:example::121122 @click.group()123 def cli():124 pass125126 @cli.command()127 def initdb():128 click.echo('Initialized the database')129130 @cli.command()131 def dropdb():132 click.echo('Dropped the database')133134You would then invoke the :class:`Group` in your setuptools entry points or135other invocations::136137 if __name__ == '__main__':138 cli()139140141Registering Commands Later142--------------------------143144Instead of using the ``@group.command()`` decorator, commands can be145decorated with the plain ``@click.command()`` decorator and registered146with a group later with ``group.add_command()``. This could be used to147split commands into multiple Python modules.148149.. code-block:: python150151 @click.command()152 def greet():153 click.echo("Hello, World!")154155.. code-block:: python156157 @click.group()158 def group():159 pass160161 group.add_command(greet)162163164Adding Parameters165-----------------166167To add parameters, use the :func:`option` and :func:`argument` decorators:168169.. click:example::170171 @click.command()172 @click.option('--count', default=1, help='number of greetings')173 @click.argument('name')174 def hello(count, name):175 for x in range(count):176 click.echo(f"Hello {name}!")177178What it looks like:179180.. click:run::181182 invoke(hello, args=['--help'], prog_name='python hello.py')183184.. _switching-to-setuptools:185186Switching to Setuptools187-----------------------188189In the code you wrote so far there is a block at the end of the file which190looks like this: ``if __name__ == '__main__':``. This is traditionally191how a standalone Python file looks like. With Click you can continue192doing that, but there are better ways through setuptools.193194There are two main (and many more) reasons for this:195196The first one is that setuptools automatically generates executable197wrappers for Windows so your command line utilities work on Windows too.198199The second reason is that setuptools scripts work with virtualenv on Unix200without the virtualenv having to be activated. This is a very useful201concept which allows you to bundle your scripts with all requirements into202a virtualenv.203204Click is perfectly equipped to work with that and in fact the rest of the205documentation will assume that you are writing applications through206setuptools.207208I strongly recommend to have a look at the :ref:`setuptools-integration`209chapter before reading the rest as the examples assume that you will210be using setuptools.