Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

280 lines · 8.4 KiB

Last changed by

Use python3 venv module instead of needing virtualenv (#2539)David Lordbefore adoptiond34d31f

History of this file

Take 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``: `Multi 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 setuptools entry points or205other invocations::206207    if __name__ == '__main__':208        cli()209210211Registering Commands Later212--------------------------213214Instead of using the ``@group.command()`` decorator, commands can be215decorated with the plain ``@click.command()`` decorator and registered216with a group later with ``group.add_command()``. This could be used to217split commands into multiple Python modules.218219.. code-block:: python220221    @click.command()222    def greet():223        click.echo("Hello, World!")224225.. code-block:: python226227    @click.group()228    def group():229        pass230231    group.add_command(greet)232233234Adding Parameters235-----------------236237To add parameters, use the :func:`option` and :func:`argument` decorators:238239.. click:example::240241    @click.command()242    @click.option('--count', default=1, help='number of greetings')243    @click.argument('name')244    def hello(count, name):245        for x in range(count):246            click.echo(f"Hello {name}!")247248What it looks like:249250.. click:run::251252    invoke(hello, args=['--help'], prog_name='python hello.py')253254.. _switching-to-setuptools:255256Switching to Setuptools257-----------------------258259In the code you wrote so far there is a block at the end of the file which260looks like this: ``if __name__ == '__main__':``.  This is traditionally261how a standalone Python file looks like.  With Click you can continue262doing that, but there are better ways through setuptools.263264There are two main (and many more) reasons for this:265266The first one is that setuptools automatically generates executable267wrappers for Windows so your command line utilities work on Windows too.268269The second reason is that setuptools scripts work with virtualenv on Unix270without the virtualenv having to be activated.  This is a very useful271concept which allows you to bundle your scripts with all requirements into272a virtualenv.273274Click is perfectly equipped to work with that and in fact the rest of the275documentation will assume that you are writing applications through276setuptools.277278I strongly recommend to have a look at the :ref:`setuptools-integration`279chapter before reading the rest as the examples assume that you will280be using setuptools.