quickstart.md
This file
Path
docs/quickstart.md
195 lines · 6.7 KiB · Markdown
Last changed by
Merge branch 'main' into fix-path-byteswarningKevin Deldyckebefore adoptiondbfb10a
History of this fileTake it
Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 1–26why, one step back1# Quickstart23```{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.Merge branch 'main' into fix-path-byteswarningKevin Deldyckebefore adoptiondbfb10a
line 27why, one step back27- [colors](https://github.com/pallets/click/tree/main/examples/colors) : A simple example that colorizes text.Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 28–82why, one step back28- [aliases](https://github.com/pallets/click/tree/main/examples/aliases) : An advanced example that implements29 {ref}`aliases`.30- [imagepipe](https://github.com/pallets/click/tree/main/examples/imagepipe) : A complex example that implements some31 {ref}`command-pipelines` . It chains together image processing instructions. Requires pillow.32- [repo](https://github.com/pallets/click/tree/main/examples/repo) : An advanced example that implements a33 Git-/Mercurial-like command line interface.34- [complex](https://github.com/pallets/click/tree/main/examples/complex) : A very advanced example that implements35 loading subcommands dynamically from a plugin folder.36- [termui](https://github.com/pallets/click/tree/main/examples/termui) : A simple example that showcases terminal UI37 helpers provided by click.3839## Basic Concepts - Creating a Command4041Click is based on declaring commands through decorators. Internally, there is a non-decorator interface for advanced use42cases, but it's discouraged for high-level usage.4344A function becomes a Click command line tool by decorating it through {func}`command`. At its simplest, just45decorating a function with this decorator will make it into a callable script:464748```{eval-rst}49.. click:example::50 import click5152 @click.command()53 def hello():54 click.echo('Hello World!')5556What's happening is that the decorator converts the function into a :class:`Command` which then can be invoked:5758.. click:example::59 if __name__ == '__main__':60 hello()6162And what it looks like:6364.. click:run::65 invoke(hello, args=[], prog_name='python hello.py')6667And the corresponding help page:6869.. click:run::70 invoke(hello, args=['--help'], prog_name='python hello.py')71```7273## Echoing7475Why does this example use {func}`echo` instead of the regular {func}`print` function? The answer to this question is76that Click attempts to support different environments consistently and to be very robust even when the environment is77misconfigured. Click wants to be functional at least on a basic level even if everything is completely broken.7879What this means is that the {func}`echo` function applies some error correction in case the terminal is misconfigured80instead of dying with a {exc}`UnicodeError`.8182The echo function also supports color and other styles in output. It will automatically remove styles if the outputMerge branch 'main' into fix-path-byteswarningKevin Deldyckebefore adoptiondbfb10a
line 83why, one step back83stream is a file. See {ref}`ansi-colors`.Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 84–143why, one step back8485If you don't need this, you can also use the `print()` construct / function.8687## Nesting Commands8889Commands can be attached to other commands of type {class}`Group`. This allows arbitrary nesting of scripts. As an90example here is a script that implements two commands for managing databases:9192```{eval-rst}93.. click:example::94 @click.group()95 def cli():96 pass9798 @click.command()99 def initdb():100 click.echo('Initialized the database')101102 @click.command()103 def dropdb():104 click.echo('Dropped the database')105106 cli.add_command(initdb)107 cli.add_command(dropdb)108```109110As you can see, the {func}`group` decorator works like the {func}`command` decorator, but creates a {class}`Group`111object instead which can be given multiple subcommands that can be attached with {meth}`Group.add_command`.112113For simple scripts, it's also possible to automatically attach and create a command by using the {meth}`Group.command`114decorator instead. The above script can instead be written like this:115116```{eval-rst}117.. click:example::118 @click.group()119 def cli():120 pass121122 @cli.command()123 def initdb():124 click.echo('Initialized the database')125126 @cli.command()127 def dropdb():128 click.echo('Dropped the database')129130You would then invoke the :class:`Group` in your entry points or other invocations:131132.. click:example::133 if __name__ == '__main__':134 cli()135```136137## Registering Commands Later138139Instead of using the `@group.command()` decorator, commands can be decorated with the plain `@command()` decorator140and registered with a group later with `group.add_command()`. This could be used to split commands into multiple Python141modules.142143```{code-block} pythonFix indentation on quickstart (#3469)David Lordbefore adoption1bd3a87
lines 144–146why, one step back144@click.command()145def greet():146 click.echo("Hello, World!")Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 147–149why, one step back147```148149```{code-block} pythonFix indentation on quickstart (#3469)David Lordbefore adoption1bd3a87
lines 150–152why, one step back150@click.group()151def group():152 passMove Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
line 153why, one step back153Fix indentation on quickstart (#3469)David Lordbefore adoption1bd3a87
line 154why, one step back154group.add_command(greet)Move Quickstart doc from reST to MyST and reinstate Utils doc directives (#3026)Rowlando13before adoption1c68e53
lines 155–195why, one step back155```156157## Adding Parameters158159To add parameters, use the {func}`option` and {func}`argument` decorators:160161```{eval-rst}162.. click:example::163 @click.command()164 @click.option('--count', default=1, help='number of greetings')165 @click.argument('name')166 def hello(count, name):167 for x in range(count):168 click.echo(f"Hello {name}!")169170What it looks like:171172.. click:run::173 invoke(hello, args=['--help'], prog_name='python hello.py')174```175176## Switching to Entry Points177178In the code you wrote so far there is a block at the end of the file which looks like this:179`if __name__ == '__main__':`. This is traditionally how a standalone Python file looks like. With Click you can continue180doing that, but a better way is to package your app with an entry point.181182There are two main (and many more) reasons for this:183184The first one is that installers automatically generate executable wrappers for Windows so your command line utilities185work on Windows too.186187The second reason is that entry point scripts work with virtualenv on Unix without the virtualenv having to be188activated. This is a very useful concept which allows you to bundle your scripts with all requirements into a189virtualenv.190191Click is perfectly equipped to work with that and in fact the rest of the documentation will assume that you are writing192applications as distributed packages.193194Look at the {doc}`entry-points` chapter before reading the rest as the examples assume that you will be using entry195points.