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
The walk stopped after 200 commits: lines older than 1cd7593 point at it.
Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 1–31why, one step back1Quickstart2==========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 toMerge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 32why, one step back32keep different project environments isolated.Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
line 33why, one step back33Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 34why, one step back34Create your project folder, then a virtualenv within it::Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 35–37why, one step back3536 $ mkdir myproject37 $ cd myprojectMerge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 38why, one step back38 $ python3 -m venv .venvMerge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 39–42why, one step back3940Now, whenever you want to work on a project, you only have to activate the41corresponding environment. On OS X and Linux, do the following::42Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
lines 43–44why, one step back43 $ . .venv/bin/activate44 (venv) $Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 45–47why, one step back4546If you are a Windows user, the following command is for you::47Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
lines 48–49why, one step back48 > .venv\scripts\activate49 (venv) >Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 50–53why, one step back5051Either way, you should now be using your virtualenv (notice how the prompt of52your shell has changed to show the active environment).53Merge branch '8.1.x'David Lordbefore adoptiond9af5cf
line 54why, one step back54And if you want to stop using the virtualenv, use the following command::Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 55–62why, one step back5556 $ 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::62use lowercase click nameRohit Goswamibefore adoption6f705dd
line 63why, one step back63 $ pip install clickMerge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 64–80why, one step back6465A 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 outputMerge remote-tracking branch 'origin/8.0.x'David Lordbefore adoption8a04bb0
line 81why, one step back81 <https://github.com/pallets/click/tree/main/examples/inout>`_Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
line 82why, one step back82* ``naval``: `Port of docopt naval exampleMerge remote-tracking branch 'origin/8.0.x'David Lordbefore adoption8a04bb0
line 83why, one step back83 <https://github.com/pallets/click/tree/main/examples/naval>`_Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
line 84why, one step back84* ``aliases``: `Command alias exampleMerge remote-tracking branch 'origin/8.0.x'David Lordbefore adoption8a04bb0
line 85why, one step back85 <https://github.com/pallets/click/tree/main/examples/aliases>`_Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
line 86why, one step back86* ``repo``: `Git-/Mercurial-like command line interfaceMerge remote-tracking branch 'origin/8.0.x'David Lordbefore adoption8a04bb0
line 87why, one step back87 <https://github.com/pallets/click/tree/main/examples/repo>`_Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
line 88why, one step back88* ``complex``: `Complex example with plugin loadingMerge remote-tracking branch 'origin/8.0.x'David Lordbefore adoption8a04bb0
line 89why, one step back89 <https://github.com/pallets/click/tree/main/examples/complex>`_Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
line 90why, one step back90* ``validation``: `Custom parameter validation exampleMerge remote-tracking branch 'origin/8.0.x'David Lordbefore adoption8a04bb0
line 91why, one step back91 <https://github.com/pallets/click/tree/main/examples/validation>`_Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
line 92why, one step back92* ``colors``: `Color support demoMerge remote-tracking branch 'origin/8.0.x'David Lordbefore adoption8a04bb0
line 93why, one step back93 <https://github.com/pallets/click/tree/main/examples/colors>`_Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
line 94why, one step back94* ``termui``: `Terminal UI functions demoMerge remote-tracking branch 'origin/8.0.x'David Lordbefore adoption8a04bb0
line 95why, one step back95 <https://github.com/pallets/click/tree/main/examples/termui>`_deprecate base classes `BaseCommand` and `MultiCommand` (#2591)David Lordbefore adoptionedcd2dc
line 96why, one step back96* ``imagepipe``: `Command chaining demoMerge remote-tracking branch 'origin/8.0.x'David Lordbefore adoption8a04bb0
line 97why, one step back97 <https://github.com/pallets/click/tree/main/examples/imagepipe>`_Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 98–146why, one step back9899Basic 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 errorMerge branch '8.1.x'David Lordbefore adoption6bd8e56
line 147why, one step back147correction in case the terminal is misconfigured instead of dying with aMerge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 148–203why, one step back148: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')203switch to flit build backend (#2543)David Lordbefore adoption3fcf338
line 204why, one step back204You would then invoke the :class:`Group` in your entry points or other invocations::Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 205–252why, one step back205206 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')252switch to flit build backend (#2543)David Lordbefore adoption3fcf338
lines 253–254why, one step back253Switching to Entry Points254-------------------------Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 255–258why, one step back255256In 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 continueswitch to flit build backend (#2543)David Lordbefore adoption3fcf338
line 259why, one step back259doing that, but a better way is to package your app with an entry point.Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 260–262why, one step back260261There are two main (and many more) reasons for this:262switch to flit build backend (#2543)David Lordbefore adoption3fcf338
line 263why, one step back263The first one is that installers automatically generate executableMerge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 264–265why, one step back264wrappers for Windows so your command line utilities work on Windows too.265switch to flit build backend (#2543)David Lordbefore adoption3fcf338
line 266why, one step back266The second reason is that entry point scripts work with virtualenv on UnixMerge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
lines 267–271why, one step back267without 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 theswitch to flit build backend (#2543)David Lordbefore adoption3fcf338
lines 272–273why, one step back272documentation will assume that you are writing applications as distributed273packages.Merge pull request #1797 from pallets/dependabot/pip/importlib-metadata-3.7.0dependabot-preview[bot]before adoption1cd7593
line 274why, one step back274switch to flit build backend (#2543)David Lordbefore adoption3fcf338
lines 275–276why, one step back275Look at the :doc:`entry-points` chapter before reading the rest as the examples276assume that you will be using entry points.