quickstart.rst
This file
Path
docs/quickstart.rst
276 lines · 8.3 KiB
Last changed by
deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
History of this fileTake it
1Quickstart2==========34.. currentmodule:: click56You can get the library directly from PyPI::78 pip install click910The installation into a :ref:`virtualenv` is heavily recommended.1112.. _virtualenv:1314virtualenv15----------1617Virtualenv is probably what you want to use for developing Click18applications.1920What problem does virtualenv solve? Chances are that you want to use it21for other projects besides your Click script. But the more projects you22have, the more likely it is that you will be working with different23versions of Python itself, or at least different versions of Python24libraries. Let's face it: quite often libraries break backwards25compatibility, and it's unlikely that any serious application will have26zero dependencies. So what do you do if two or more of your projects have27conflicting dependencies?2829Virtualenv to the rescue! Virtualenv enables multiple side-by-side30installations of Python, one for each project. It doesn't actually31install separate copies of Python, but it does provide a clever way to32keep different project environments isolated.3334Create your project folder, then a virtualenv within it::3536 $ mkdir myproject37 $ cd myproject38 $ python3 -m venv .venv3940Now, whenever you want to work on a project, you only have to activate the41corresponding environment. On OS X and Linux, do the following::4243 $ . .venv/bin/activate44 (venv) $4546If you are a Windows user, the following command is for you::4748 > .venv\scripts\activate49 (venv) >5051Either way, you should now be using your virtualenv (notice how the prompt of52your shell has changed to show the active environment).5354And if you want to stop using the virtualenv, use the following command::5556 $ deactivate5758After doing this, the prompt of your shell should be as familiar as before.5960Now, let's move on. Enter the following command to get Click activated in your61virtualenv::6263 $ pip install click6465A few seconds later and you are good to go.6667Screencast and Examples68-----------------------6970There is a screencast available which shows the basic API of Click and71how to build simple applications with it. It also explores how to build72commands with subcommands.7374* `Building Command Line Applications with Click75 <https://www.youtube.com/watch?v=kNke39OZ2k0>`_7677Examples of Click applications can be found in the documentation as well78as in the GitHub repository together with readme files:7980* ``inout``: `File input and output81 <https://github.com/pallets/click/tree/main/examples/inout>`_82* ``naval``: `Port of docopt naval example83 <https://github.com/pallets/click/tree/main/examples/naval>`_84* ``aliases``: `Command alias example85 <https://github.com/pallets/click/tree/main/examples/aliases>`_86* ``repo``: `Git-/Mercurial-like command line interface87 <https://github.com/pallets/click/tree/main/examples/repo>`_88* ``complex``: `Complex example with plugin loading89 <https://github.com/pallets/click/tree/main/examples/complex>`_90* ``validation``: `Custom parameter validation example91 <https://github.com/pallets/click/tree/main/examples/validation>`_92* ``colors``: `Color support demo93 <https://github.com/pallets/click/tree/main/examples/colors>`_94* ``termui``: `Terminal UI functions demo95 <https://github.com/pallets/click/tree/main/examples/termui>`_96* ``imagepipe``: `Command chaining demo97 <https://github.com/pallets/click/tree/main/examples/imagepipe>`_9899Basic Concepts - Creating a Command100-----------------------------------101102Click is based on declaring commands through decorators. Internally, there103is a non-decorator interface for advanced use cases, but it's discouraged104for high-level usage.105106A function becomes a Click command line tool by decorating it through107:func:`click.command`. At its simplest, just decorating a function108with this decorator will make it into a callable script:109110.. click:example::111112 import click113114 @click.command()115 def hello():116 click.echo('Hello World!')117118What's happening is that the decorator converts the function into a119:class:`Command` which then can be invoked::120121 if __name__ == '__main__':122 hello()123124And what it looks like:125126.. click:run::127128 invoke(hello, args=[], prog_name='python hello.py')129130And the corresponding help page:131132.. click:run::133134 invoke(hello, args=['--help'], prog_name='python hello.py')135136Echoing137-------138139Why does this example use :func:`echo` instead of the regular140:func:`print` function? The answer to this question is that Click141attempts to support different environments consistently and to be very142robust even when the environment is misconfigured. Click wants to be143functional at least on a basic level even if everything is completely144broken.145146What this means is that the :func:`echo` function applies some error147correction in case the terminal is misconfigured instead of dying with a148:exc:`UnicodeError`.149150The echo function also supports color and other styles in output. It151will automatically remove styles if the output stream is a file. On152Windows, colorama is automatically installed and used. See153:ref:`ansi-colors`.154155If you don't need this, you can also use the `print()` construct /156function.157158Nesting Commands159----------------160161Commands can be attached to other commands of type :class:`Group`. This162allows arbitrary nesting of scripts. As an example here is a script that163implements two commands for managing databases:164165.. click:example::166167 @click.group()168 def cli():169 pass170171 @click.command()172 def initdb():173 click.echo('Initialized the database')174175 @click.command()176 def dropdb():177 click.echo('Dropped the database')178179 cli.add_command(initdb)180 cli.add_command(dropdb)181182As you can see, the :func:`group` decorator works like the :func:`command`183decorator, but creates a :class:`Group` object instead which can be given184multiple subcommands that can be attached with :meth:`Group.add_command`.185186For simple scripts, it's also possible to automatically attach and create a187command by using the :meth:`Group.command` decorator instead. The above188script can instead be written like this:189190.. click:example::191192 @click.group()193 def cli():194 pass195196 @cli.command()197 def initdb():198 click.echo('Initialized the database')199200 @cli.command()201 def dropdb():202 click.echo('Dropped the database')203204You would then invoke the :class:`Group` in your entry points or other invocations::205206 if __name__ == '__main__':207 cli()208209210Registering Commands Later211--------------------------212213Instead of using the ``@group.command()`` decorator, commands can be214decorated with the plain ``@click.command()`` decorator and registered215with a group later with ``group.add_command()``. This could be used to216split commands into multiple Python modules.217218.. code-block:: python219220 @click.command()221 def greet():222 click.echo("Hello, World!")223224.. code-block:: python225226 @click.group()227 def group():228 pass229230 group.add_command(greet)231232233Adding Parameters234-----------------235236To add parameters, use the :func:`option` and :func:`argument` decorators:237238.. click:example::239240 @click.command()241 @click.option('--count', default=1, help='number of greetings')242 @click.argument('name')243 def hello(count, name):244 for x in range(count):245 click.echo(f"Hello {name}!")246247What it looks like:248249.. click:run::250251 invoke(hello, args=['--help'], prog_name='python hello.py')252253Switching to Entry Points254-------------------------255256In the code you wrote so far there is a block at the end of the file which257looks like this: ``if __name__ == '__main__':``. This is traditionally258how a standalone Python file looks like. With Click you can continue259doing that, but a better way is to package your app with an entry point.260261There are two main (and many more) reasons for this:262263The first one is that installers automatically generate executable264wrappers for Windows so your command line utilities work on Windows too.265266The second reason is that entry point scripts work with virtualenv on Unix267without the virtualenv having to be activated. This is a very useful268concept which allows you to bundle your scripts with all requirements into269a virtualenv.270271Click is perfectly equipped to work with that and in fact the rest of the272documentation will assume that you are writing applications as distributed273packages.274275Look at the :doc:`entry-points` chapter before reading the rest as the examples276assume that you will be using entry points.