quickstart.rst
This file
Path
docs/quickstart.rst
275 lines · 8.7 KiB
Last changed by
Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
History of this fileTake it
The walk stopped after 200 commits: lines older than 7eb990f point at it.
Make locale optional (Fixes #880)Armin Ronacherbefore adoption7eb990f
lines 1–34why, 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 to32keep different project environments isolated. Let's see how virtualenv33works.34Merge pull request #1161 from jdufresne/easyDavid Lordbefore adoption7d19964
line 35why, one step back35If you are on Mac OS X or Linux::Make locale optional (Fixes #880)Armin Ronacherbefore adoption7eb990f
line 36why, one step back36Merge branch '7.x'David Lordbefore adoption2269786
line 37why, one step back37 $ pip install virtualenv --userMake locale optional (Fixes #880)Armin Ronacherbefore adoption7eb990f
lines 38–48why, one step back3839One 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.48Merge branch '7.x'David Lordbefore adoption11abf2b
line 49why, one step back49.. _installing pip: https://pip.readthedocs.io/en/latest/installing/Make locale optional (Fixes #880)Armin Ronacherbefore adoption7eb990f
lines 50–117why, one step back5051Once 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/master/examples/inout>`_101* ``naval``: `Port of docopt naval example102 <https://github.com/pallets/click/tree/master/examples/naval>`_103* ``aliases``: `Command alias example104 <https://github.com/pallets/click/tree/master/examples/aliases>`_105* ``repo``: `Git-/Mercurial-like command line interface106 <https://github.com/pallets/click/tree/master/examples/repo>`_107* ``complex``: `Complex example with plugin loading108 <https://github.com/pallets/click/tree/master/examples/complex>`_109* ``validation``: `Custom parameter validation example110 <https://github.com/pallets/click/tree/master/examples/validation>`_111* ``colors``: `Colorama ANSI color support112 <https://github.com/pallets/click/tree/master/examples/colors>`_113* ``termui``: `Terminal UI functions demo114 <https://github.com/pallets/click/tree/master/examples/termui>`_115* ``imagepipe``: `Multi command chaining demo116 <https://github.com/pallets/click/tree/master/examples/imagepipe>`_117Merge pull request #1009 from dougharris/parameter-949Dan Sullybefore adoptionbf30737
lines 118–119why, one step back118Basic Concepts - Creating a Command119-----------------------------------Make locale optional (Fixes #880)Armin Ronacherbefore adoption7eb990f
lines 120–159why, one step back120121Click 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 ClickMerge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 160why, one step back160attempts to support different environments consistently and to be veryMake locale optional (Fixes #880)Armin Ronacherbefore adoption7eb990f
lines 161–171why, one step back161robust 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`.168169As an added benefit, starting with Click 2.0, the echo function also170has good support for ANSI colors. It will automatically strip ANSI codes171if the output stream is a file and if colorama is supported, ANSI colorsMerge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 172why, one step back172will also work on Windows. See :ref:`ansi-colors`.Make locale optional (Fixes #880)Armin Ronacherbefore adoption7eb990f
lines 173–222why, one step back173174If 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')222Merge pull request #1117 from sirosen/docs/tweak-quickstartDavid Lordbefore adoption6e410dc
lines 223–228why, one step back223You would then invoke the :class:`Group` in your setuptools entry points or224other invocations::225226 if __name__ == '__main__':227 cli()228Make locale optional (Fixes #880)Armin Ronacherbefore adoption7eb990f
lines 229–240why, one step back229Adding Parameters230-----------------231232To add parameters, use the :func:`option` and :func:`argument` decorators:233234.. click:example::235236 @click.command()237 @click.option('--count', default=1, help='number of greetings')238 @click.argument('name')239 def hello(count, name):240 for x in range(count):Merge pull request #1532 from pallets/drop-python2David Lordbefore adoption97de2c9
line 241why, one step back241 click.echo(f"Hello {name}!")Make locale optional (Fixes #880)Armin Ronacherbefore adoption7eb990f
lines 242–275why, one step back242243What it looks like:244245.. click:run::246247 invoke(hello, args=['--help'], prog_name='python hello.py')248249.. _switching-to-setuptools:250251Switching to Setuptools252-----------------------253254In the code you wrote so far there is a block at the end of the file which255looks like this: ``if __name__ == '__main__':``. This is traditionally256how a standalone Python file looks like. With Click you can continue257doing that, but there are better ways through setuptools.258259There are two main (and many more) reasons for this:260261The first one is that setuptools automatically generates executable262wrappers for Windows so your command line utilities work on Windows too.263264The second reason is that setuptools scripts work with virtualenv on Unix265without the virtualenv having to be activated. This is a very useful266concept which allows you to bundle your scripts with all requirements into267a virtualenv.268269Click is perfectly equipped to work with that and in fact the rest of the270documentation will assume that you are writing applications through271setuptools.272273I strongly recommend to have a look at the :ref:`setuptools-integration`274chapter before reading the rest as the examples assume that you will275be using setuptools.