Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

276 lines · 8.8 KiB

Last changed by

Merge pull request #1009 from dougharris/parameter-949Dan Sullybefore adoptionbf30737

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.  Let's see how virtualenv33works.3435If you are on Mac OS X or Linux, chances are that one of the following two36commands will work for you::3738    $ sudo easy_install virtualenv3940or even better::4142    $ sudo pip install virtualenv4344One of these will probably install virtualenv on your system.  Maybe it's even45in your package manager.  If you use Ubuntu, try::4647    $ sudo apt-get install python-virtualenv4849If you are on Windows (or none of the above methods worked) you must install50``pip`` first.  For more information about this, see `installing pip`_.51Once you have it installed, run the ``pip`` command from above, but without52the `sudo` prefix.5354.. _installing pip: https://pip.readthedocs.io/en/latest/installing.html5556Once you have virtualenv installed, just fire up a shell and create57your own environment.  I usually create a project folder and a `venv`58folder within::5960    $ mkdir myproject61    $ cd myproject62    $ virtualenv venv63    New python executable in venv/bin/python64    Installing setuptools, pip............done.6566Now, whenever you want to work on a project, you only have to activate the67corresponding environment.  On OS X and Linux, do the following::6869    $ . venv/bin/activate7071If you are a Windows user, the following command is for you::7273    $ venv\scripts\activate7475Either way, you should now be using your virtualenv (notice how the prompt of76your shell has changed to show the active environment).7778And if you want to go back to the real world, use the following command::7980    $ deactivate8182After doing this, the prompt of your shell should be as familiar as before.8384Now, let's move on. Enter the following command to get Click activated in your85virtualenv::8687    $ pip install Click8889A few seconds later and you are good to go.9091Screencast and Examples92-----------------------9394There is a screencast available which shows the basic API of Click and95how to build simple applications with it.  It also explores how to build96commands with subcommands.9798*   `Building Command Line Applications with Click99    <https://www.youtube.com/watch?v=kNke39OZ2k0>`_100101Examples of Click applications can be found in the documentation as well102as in the GitHub repository together with readme files:103104*   ``inout``: `File input and output105    <https://github.com/pallets/click/tree/master/examples/inout>`_106*   ``naval``: `Port of docopt naval example107    <https://github.com/pallets/click/tree/master/examples/naval>`_108*   ``aliases``: `Command alias example109    <https://github.com/pallets/click/tree/master/examples/aliases>`_110*   ``repo``: `Git-/Mercurial-like command line interface111    <https://github.com/pallets/click/tree/master/examples/repo>`_112*   ``complex``: `Complex example with plugin loading113    <https://github.com/pallets/click/tree/master/examples/complex>`_114*   ``validation``: `Custom parameter validation example115    <https://github.com/pallets/click/tree/master/examples/validation>`_116*   ``colors``: `Colorama ANSI color support117    <https://github.com/pallets/click/tree/master/examples/colors>`_118*   ``termui``: `Terminal UI functions demo119    <https://github.com/pallets/click/tree/master/examples/termui>`_120*   ``imagepipe``: `Multi command chaining demo121    <https://github.com/pallets/click/tree/master/examples/imagepipe>`_122123Basic Concepts - Creating a Command124-----------------------------------125126Click is based on declaring commands through decorators.  Internally, there127is a non-decorator interface for advanced use cases, but it's discouraged128for high-level usage.129130A function becomes a Click command line tool by decorating it through131:func:`click.command`.  At its simplest, just decorating a function132with this decorator will make it into a callable script:133134.. click:example::135136    import click137138    @click.command()139    def hello():140        click.echo('Hello World!')141142What's happening is that the decorator converts the function into a143:class:`Command` which then can be invoked::144145    if __name__ == '__main__':146        hello()147148And what it looks like:149150.. click:run::151152    invoke(hello, args=[], prog_name='python hello.py')153154And the corresponding help page:155156.. click:run::157158    invoke(hello, args=['--help'], prog_name='python hello.py')159160Echoing161-------162163Why does this example use :func:`echo` instead of the regular164:func:`print` function?  The answer to this question is that Click165attempts to support both Python 2 and Python 3 the same way and to be very166robust even when the environment is misconfigured.  Click wants to be167functional at least on a basic level even if everything is completely168broken.169170What this means is that the :func:`echo` function applies some error171correction in case the terminal is misconfigured instead of dying with an172:exc:`UnicodeError`.173174As an added benefit, starting with Click 2.0, the echo function also175has good support for ANSI colors.  It will automatically strip ANSI codes176if the output stream is a file and if colorama is supported, ANSI colors177will also work on Windows. Note that in Python 2, the :func:`echo` function178does not parse color code information from bytearrays. See :ref:`ansi-colors`179for more information.180181If you don't need this, you can also use the `print()` construct /182function.183184Nesting Commands185----------------186187Commands can be attached to other commands of type :class:`Group`.  This188allows arbitrary nesting of scripts.  As an example here is a script that189implements two commands for managing databases:190191.. click:example::192193    @click.group()194    def cli():195        pass196197    @click.command()198    def initdb():199        click.echo('Initialized the database')200201    @click.command()202    def dropdb():203        click.echo('Dropped the database')204205    cli.add_command(initdb)206    cli.add_command(dropdb)207208As you can see, the :func:`group` decorator works like the :func:`command`209decorator, but creates a :class:`Group` object instead which can be given210multiple subcommands that can be attached with :meth:`Group.add_command`.211212For simple scripts, it's also possible to automatically attach and create a213command by using the :meth:`Group.command` decorator instead.  The above214script can instead be written like this:215216.. click:example::217218    @click.group()219    def cli():220        pass221222    @cli.command()223    def initdb():224        click.echo('Initialized the database')225226    @cli.command()227    def dropdb():228        click.echo('Dropped the database')229230Adding Parameters231-----------------232233To add parameters, use the :func:`option` and :func:`argument` decorators:234235.. click:example::236237    @click.command()238    @click.option('--count', default=1, help='number of greetings')239    @click.argument('name')240    def hello(count, name):241        for x in range(count):242            click.echo('Hello %s!' % name)243244What it looks like:245246.. click:run::247248    invoke(hello, args=['--help'], prog_name='python hello.py')249250.. _switching-to-setuptools:251252Switching to Setuptools253-----------------------254255In the code you wrote so far there is a block at the end of the file which256looks like this: ``if __name__ == '__main__':``.  This is traditionally257how a standalone Python file looks like.  With Click you can continue258doing that, but there are better ways through setuptools.259260There are two main (and many more) reasons for this:261262The first one is that setuptools automatically generates executable263wrappers for Windows so your command line utilities work on Windows too.264265The second reason is that setuptools scripts work with virtualenv on Unix266without the virtualenv having to be activated.  This is a very useful267concept which allows you to bundle your scripts with all requirements into268a virtualenv.269270Click is perfectly equipped to work with that and in fact the rest of the271documentation will assume that you are writing applications through272setuptools.273274I strongly recommend to have a look at the :ref:`setuptools-integration`275chapter before reading the rest as the examples assume that you will276be using setuptools.