Skip to content
Myr

quickstart.rst

This file

Path

docs/quickstart.rst

282 lines · 8.9 KiB

Last changed by

Merge pull request #1454 from ppartarr/patch-1Dan Sullybefore adoption2a5e8a9

History of this file

Take it

The walk stopped after 200 commits: lines older than 430c50a point at it.

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 1–41why, one step back
1Quickstart
2==========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::41

Merge pull request #1454 from ppartarr/patch-1Dan Sullybefore adoption2a5e8a9

line 42why, one step back
42 $ pip install virtualenv --user

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 43–53why, one step back
43
44One 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.53

reformat changelog, update docs configDavid Lordbefore adoption02756dd

line 54why, one step back
54.. _installing pip: https://pip.readthedocs.io/en/latest/installing/

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 55–122why, one step back
55
56Once 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>`_122

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

lines 123–124why, one step back
123Basic Concepts - Creating a Command
124-----------------------------------

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 125–176why, one step back
125
126Click 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 colors

Merge pull request #1010 from rpgraham84/masterDan Sullybefore adoption692cb32

lines 177–179why, one step back
177will also work on Windows. Note that in Python 2, the :func:`echo` function
178does not parse color code information from bytearrays. See :ref:`ansi-colors`179for more information.

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 180–229why, one step back
180
181If 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')229

Merge pull request #1117 from sirosen/docs/tweak-quickstartDavid Lordbefore adoption6e410dc

lines 230–235why, one step back
230You would then invoke the :class:`Group` in your setuptools entry points or
231other invocations::232233 if __name__ == '__main__':234 cli()235

Merge pull request #681 from pgkelley4/masterMarkus Unterwaditzerbefore adoption430c50a

lines 236–282why, one step back
236Adding Parameters
237-----------------238239To add parameters, use the :func:`option` and :func:`argument` decorators:240241.. click:example::242243 @click.command()244 @click.option('--count', default=1, help='number of greetings')245 @click.argument('name')246 def hello(count, name):247 for x in range(count):248 click.echo('Hello %s!' % name)249250What it looks like:251252.. click:run::253254 invoke(hello, args=['--help'], prog_name='python hello.py')255256.. _switching-to-setuptools:257258Switching to Setuptools259-----------------------260261In the code you wrote so far there is a block at the end of the file which262looks like this: ``if __name__ == '__main__':``. This is traditionally263how a standalone Python file looks like. With Click you can continue264doing that, but there are better ways through setuptools.265266There are two main (and many more) reasons for this:267268The first one is that setuptools automatically generates executable269wrappers for Windows so your command line utilities work on Windows too.270271The second reason is that setuptools scripts work with virtualenv on Unix272without the virtualenv having to be activated. This is a very useful273concept which allows you to bundle your scripts with all requirements into274a virtualenv.275276Click is perfectly equipped to work with that and in fact the rest of the277documentation will assume that you are writing applications through278setuptools.279280I strongly recommend to have a look at the :ref:`setuptools-integration`281chapter before reading the rest as the examples assume that you will282be using setuptools.