Skip to content
Myr

quickstart.md

This file

Path

docs/quickstart.md

196 lines · 6.7 KiB · Markdown

Last changed by

Merge branch 'stable'David Lordbefore adoptiona9a218c

History of this file

Take it

Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53

lines 1–144why, one step back
1# Quickstart
23```{currentmodule} click4```56## Install78Install from PyPI:910```console11pip install click12```1314Installing into a virtual environment is highly recommended. We suggest {ref}`virtualenv-heading`.1516## Examples1718Some standalone examples of Click applications are packaged with Click. They are available in the19[examples folder](https://github.com/pallets/click/tree/main/examples) of the repo.2021- [inout](https://github.com/pallets/click/tree/main/examples/inout) : A very simple example of an application that can22 read from files and write to files and also accept input from stdin or write to stdout.23- [validation](https://github.com/pallets/click/tree/main/examples/validation) : A simple example of an application that24 performs custom validation of parameters in different ways.25- [naval](https://github.com/pallets/click/tree/main/examples/naval) : Port of the [docopt](http://docopt.org/) naval26 example.27- [colors](https://github.com/pallets/click/tree/main/examples/colors) : A simple example that colorizes text. Uses28 colorama on Windows.29- [aliases](https://github.com/pallets/click/tree/main/examples/aliases) : An advanced example that implements30 {ref}`aliases`.31- [imagepipe](https://github.com/pallets/click/tree/main/examples/imagepipe) : A complex example that implements some32 {ref}`command-pipelines` . It chains together image processing instructions. Requires pillow.33- [repo](https://github.com/pallets/click/tree/main/examples/repo) : An advanced example that implements a34 Git-/Mercurial-like command line interface.35- [complex](https://github.com/pallets/click/tree/main/examples/complex) : A very advanced example that implements36 loading subcommands dynamically from a plugin folder.37- [termui](https://github.com/pallets/click/tree/main/examples/termui) : A simple example that showcases terminal UI38 helpers provided by click.3940## Basic Concepts - Creating a Command4142Click is based on declaring commands through decorators. Internally, there is a non-decorator interface for advanced use43cases, but it's discouraged for high-level usage.4445A function becomes a Click command line tool by decorating it through {func}`command`. At its simplest, just46decorating a function with this decorator will make it into a callable script:474849```{eval-rst}50.. click:example::51 import click5253 @click.command()54 def hello():55 click.echo('Hello World!')5657What's happening is that the decorator converts the function into a :class:`Command` which then can be invoked:5859.. click:example::60 if __name__ == '__main__':61 hello()6263And what it looks like:6465.. click:run::66 invoke(hello, args=[], prog_name='python hello.py')6768And the corresponding help page:6970.. click:run::71 invoke(hello, args=['--help'], prog_name='python hello.py')72```7374## Echoing7576Why does this example use {func}`echo` instead of the regular {func}`print` function? The answer to this question is77that Click attempts to support different environments consistently and to be very robust even when the environment is78misconfigured. Click wants to be functional at least on a basic level even if everything is completely broken.7980What this means is that the {func}`echo` function applies some error correction in case the terminal is misconfigured81instead of dying with a {exc}`UnicodeError`.8283The echo function also supports color and other styles in output. It will automatically remove styles if the output84stream is a file. On Windows, colorama is automatically installed and used. See {ref}`ansi-colors`.8586If you don't need this, you can also use the `print()` construct / function.8788## Nesting Commands8990Commands can be attached to other commands of type {class}`Group`. This allows arbitrary nesting of scripts. As an91example here is a script that implements two commands for managing databases:9293```{eval-rst}94.. click:example::95 @click.group()96 def cli():97 pass9899 @click.command()100 def initdb():101 click.echo('Initialized the database')102103 @click.command()104 def dropdb():105 click.echo('Dropped the database')106107 cli.add_command(initdb)108 cli.add_command(dropdb)109```110111As you can see, the {func}`group` decorator works like the {func}`command` decorator, but creates a {class}`Group`112object instead which can be given multiple subcommands that can be attached with {meth}`Group.add_command`.113114For simple scripts, it's also possible to automatically attach and create a command by using the {meth}`Group.command`115decorator instead. The above script can instead be written like this:116117```{eval-rst}118.. click:example::119 @click.group()120 def cli():121 pass122123 @cli.command()124 def initdb():125 click.echo('Initialized the database')126127 @cli.command()128 def dropdb():129 click.echo('Dropped the database')130131You would then invoke the :class:`Group` in your entry points or other invocations:132133.. click:example::134 if __name__ == '__main__':135 cli()136```137138## Registering Commands Later139140Instead of using the `@group.command()` decorator, commands can be decorated with the plain `@command()` decorator141and registered with a group later with `group.add_command()`. This could be used to split commands into multiple Python142modules.143144```{code-block} python

Merge branch 'stable'David Lordbefore adoptiona9a218c

lines 145–147why, one step back
145@click.command()
146def greet():147 click.echo("Hello, World!")

Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53

lines 148–150why, one step back
148```
149150```{code-block} python

Merge branch 'stable'David Lordbefore adoptiona9a218c

lines 151–153why, one step back
151@click.group()
152def group():153 pass

Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53

line 154why, one step back
154

Merge branch 'stable'David Lordbefore adoptiona9a218c

line 155why, one step back
155group.add_command(greet)

Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53

lines 156–196why, one step back
156```
157158## Adding Parameters159160To add parameters, use the {func}`option` and {func}`argument` decorators:161162```{eval-rst}163.. click:example::164 @click.command()165 @click.option('--count', default=1, help='number of greetings')166 @click.argument('name')167 def hello(count, name):168 for x in range(count):169 click.echo(f"Hello {name}!")170171What it looks like:172173.. click:run::174 invoke(hello, args=['--help'], prog_name='python hello.py')175```176177## Switching to Entry Points178179In the code you wrote so far there is a block at the end of the file which looks like this:180`if __name__ == '__main__':`. This is traditionally how a standalone Python file looks like. With Click you can continue181doing that, but a better way is to package your app with an entry point.182183There are two main (and many more) reasons for this:184185The first one is that installers automatically generate executable wrappers for Windows so your command line utilities186work on Windows too.187188The second reason is that entry point scripts work with virtualenv on Unix without the virtualenv having to be189activated. This is a very useful concept which allows you to bundle your scripts with all requirements into a190virtualenv.191192Click is perfectly equipped to work with that and in fact the rest of the documentation will assume that you are writing193applications as distributed packages.194195Look at the {doc}`entry-points` chapter before reading the rest as the examples assume that you will be using entry196points.