quickstart.rst
This file
Path
docs/quickstart.rst
299 lines · 9.1 KiB
Last changed by
Merge pull request #1881 from pallets/default-branchDavid Lordbefore adoptionf918a71
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. Let's see how virtualenv33works.3435If you are on Mac OS X or Linux::3637 $ pip install virtualenv --user3839One of these will probably install virtualenv on your system. Maybe it's even40in your package manager. If you use Ubuntu, try::4142 $ sudo apt-get install python-virtualenv4344If you are on Windows (or none of the above methods worked) you must install45``pip`` first. For more information about this, see `installing pip`_.46Once you have it installed, run the ``pip`` command from above, but without47the `sudo` prefix.4849.. _installing pip: https://pip.readthedocs.io/en/latest/installing/5051Once you have virtualenv installed, just fire up a shell and create52your own environment. I usually create a project folder and a `venv`53folder within::5455 $ mkdir myproject56 $ cd myproject57 $ virtualenv venv58 New python executable in venv/bin/python59 Installing setuptools, pip............done.6061Now, whenever you want to work on a project, you only have to activate the62corresponding environment. On OS X and Linux, do the following::6364 $ . venv/bin/activate6566If you are a Windows user, the following command is for you::6768 $ venv\scripts\activate6970Either way, you should now be using your virtualenv (notice how the prompt of71your shell has changed to show the active environment).7273And if you want to go back to the real world, use the following command::7475 $ deactivate7677After doing this, the prompt of your shell should be as familiar as before.7879Now, let's move on. Enter the following command to get Click activated in your80virtualenv::8182 $ pip install click8384A few seconds later and you are good to go.8586Screencast and Examples87-----------------------8889There is a screencast available which shows the basic API of Click and90how to build simple applications with it. It also explores how to build91commands with subcommands.9293* `Building Command Line Applications with Click94 <https://www.youtube.com/watch?v=kNke39OZ2k0>`_9596Examples of Click applications can be found in the documentation as well97as in the GitHub repository together with readme files:9899* ``inout``: `File input and output100 <https://github.com/pallets/click/tree/main/examples/inout>`_101* ``naval``: `Port of docopt naval example102 <https://github.com/pallets/click/tree/main/examples/naval>`_103* ``aliases``: `Command alias example104 <https://github.com/pallets/click/tree/main/examples/aliases>`_105* ``repo``: `Git-/Mercurial-like command line interface106 <https://github.com/pallets/click/tree/main/examples/repo>`_107* ``complex``: `Complex example with plugin loading108 <https://github.com/pallets/click/tree/main/examples/complex>`_109* ``validation``: `Custom parameter validation example110 <https://github.com/pallets/click/tree/main/examples/validation>`_111* ``colors``: `Color support demo112 <https://github.com/pallets/click/tree/main/examples/colors>`_113* ``termui``: `Terminal UI functions demo114 <https://github.com/pallets/click/tree/main/examples/termui>`_115* ``imagepipe``: `Multi command chaining demo116 <https://github.com/pallets/click/tree/main/examples/imagepipe>`_117118Basic Concepts - Creating a Command119-----------------------------------120121Click is based on declaring commands through decorators. Internally, there122is a non-decorator interface for advanced use cases, but it's discouraged123for high-level usage.124125A function becomes a Click command line tool by decorating it through126:func:`click.command`. At its simplest, just decorating a function127with this decorator will make it into a callable script:128129.. click:example::130131 import click132133 @click.command()134 def hello():135 click.echo('Hello World!')136137What's happening is that the decorator converts the function into a138:class:`Command` which then can be invoked::139140 if __name__ == '__main__':141 hello()142143And what it looks like:144145.. click:run::146147 invoke(hello, args=[], prog_name='python hello.py')148149And the corresponding help page:150151.. click:run::152153 invoke(hello, args=['--help'], prog_name='python hello.py')154155Echoing156-------157158Why does this example use :func:`echo` instead of the regular159:func:`print` function? The answer to this question is that Click160attempts to support different environments consistently and to be very161robust even when the environment is misconfigured. Click wants to be162functional at least on a basic level even if everything is completely163broken.164165What this means is that the :func:`echo` function applies some error166correction in case the terminal is misconfigured instead of dying with an167:exc:`UnicodeError`.168169The echo function also supports color and other styles in output. It170will automatically remove styles if the output stream is a file. On171Windows, colorama is automatically installed and used. See172:ref:`ansi-colors`.173174If you don't need this, you can also use the `print()` construct /175function.176177Nesting Commands178----------------179180Commands can be attached to other commands of type :class:`Group`. This181allows arbitrary nesting of scripts. As an example here is a script that182implements two commands for managing databases:183184.. click:example::185186 @click.group()187 def cli():188 pass189190 @click.command()191 def initdb():192 click.echo('Initialized the database')193194 @click.command()195 def dropdb():196 click.echo('Dropped the database')197198 cli.add_command(initdb)199 cli.add_command(dropdb)200201As you can see, the :func:`group` decorator works like the :func:`command`202decorator, but creates a :class:`Group` object instead which can be given203multiple subcommands that can be attached with :meth:`Group.add_command`.204205For simple scripts, it's also possible to automatically attach and create a206command by using the :meth:`Group.command` decorator instead. The above207script can instead be written like this:208209.. click:example::210211 @click.group()212 def cli():213 pass214215 @cli.command()216 def initdb():217 click.echo('Initialized the database')218219 @cli.command()220 def dropdb():221 click.echo('Dropped the database')222223You would then invoke the :class:`Group` in your setuptools entry points or224other invocations::225226 if __name__ == '__main__':227 cli()228229230Registering Commands Later231--------------------------232233Instead of using the ``@group.command()`` decorator, commands can be234decorated with the plain ``@click.command()`` decorator and registered235with a group later with ``group.add_command()``. This could be used to236split commands into multiple Python modules.237238.. code-block:: python239240 @click.command()241 def greet():242 click.echo("Hello, World!")243244.. code-block:: python245246 @click.group()247 def group():248 pass249250 group.add_command(greet)251252253Adding Parameters254-----------------255256To add parameters, use the :func:`option` and :func:`argument` decorators:257258.. click:example::259260 @click.command()261 @click.option('--count', default=1, help='number of greetings')262 @click.argument('name')263 def hello(count, name):264 for x in range(count):265 click.echo(f"Hello {name}!")266267What it looks like:268269.. click:run::270271 invoke(hello, args=['--help'], prog_name='python hello.py')272273.. _switching-to-setuptools:274275Switching to Setuptools276-----------------------277278In the code you wrote so far there is a block at the end of the file which279looks like this: ``if __name__ == '__main__':``. This is traditionally280how a standalone Python file looks like. With Click you can continue281doing that, but there are better ways through setuptools.282283There are two main (and many more) reasons for this:284285The first one is that setuptools automatically generates executable286wrappers for Windows so your command line utilities work on Windows too.287288The second reason is that setuptools scripts work with virtualenv on Unix289without the virtualenv having to be activated. This is a very useful290concept which allows you to bundle your scripts with all requirements into291a virtualenv.292293Click is perfectly equipped to work with that and in fact the rest of the294documentation will assume that you are writing applications through295setuptools.296297I strongly recommend to have a look at the :ref:`setuptools-integration`298chapter before reading the rest as the examples assume that you will299be using setuptools.