:sparkles: Docs for Typer CLI (#64)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* :sparkles: Add docs for Typer CLI * :memo: Update references to Typer CLI in docs * :wrench: Update tests to check files and linting before tests, to error out early * :memo: Sync README.md with docs/index.md
authored by Sebastián Ramírez · committed by GitHub · parent 87fe78c · Browse files · 8 files·+491 added−15 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+491 added−15 removed
- other:+491 added−15 removed
Provenance
- Commit
96731c4- Tree
9cd62e0- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
87fe78c
8 files changed+491 added−15 removed
modified:docs/tutorial/first-steps.md+39 added
434 unmodified lines435 436 And we'll use ***CLI option*** to refer to those *CLI parameters* that depend on a name that starts with `--` (like `--lastname`). That are **optional** by default.437 438 We will use ***CLI parameter*** to refer to both, *CLI arguments* and *CLI options*.439+440+## **Typer CLI**441+442+Now that you know the basics of **Typer**, you might want to install and use [Typer CLI](../typer-cli.md){.internal-link target=_blank}.443+444+**Typer CLI** is a tool to run your **Typer** scripts giving you ✨ auto completion ✨ in your terminal.445+446+As an alternative to running with Python:447+448+<div class="termy">449+450+```console451+$ python main.py452+453+Hello World454+```455+456+</div>457+458+You can run with **Typer CLI**:459+460+<div class="termy">461+462+```console463+$ typer main.py run464+465+Hello World466+```467+468+</div>469+470+...and it will give you auto completion in your terminal when you hit <kbd>TAB</kbd> for all your code.471+472+So you can use it to have auto completion as you continue with the tutorial.473+474+!!! tip475+ Your CLI application built with **Typer** won't need [Typer CLI](../typer-cli.md){.internal-link target=_blank} to have auto completion once you create a Python package.476+477+ But for short scripts and for learning, before creating a Python package, it might be useful.modified:docs/tutorial/index.md+2 added-2 removed
55 unmodified lines5657585960606162626364656610 unmodified lines55 unmodified linesYou can learn a lot more by running some examples and playing around with them than by reading all the docs here.
---
## Install Typer## Install **Typer**
The first step is to install Typer.The first step is to install **Typer**.
For the tutorial, you might want to install it with all the optional dependencies and features:
<div class="termy">10 unmodified linesmodified:docs/features.md+4 added-4 removed
42 unmodified lines434445464747484949505152535253545556575859606162636413 unmodified lines42 unmodified linesThe resulting CLI apps created with **Typer** have the nice features of many "pro" command line programs you probably already love.
* Automatic help options for the main CLI program and all the its subcommands.* Automatic command and subcommand structure handling (you will see more about subcommands in the Tutorial - User Guide).* Automatic autocompletion for the CLI app in all operating systems, in all the shells (Bash, Zsh, Fish, PowerShell), so that the final user of your app can just hit <kbd>TAB</kbd> and get the available options or subcommands. ** Automatic completion for the CLI app in all operating systems, in all the shells (Bash, Zsh, Fish, PowerShell), so that the final user of your app can just hit <kbd>TAB</kbd> and get the available options or subcommands. *
!!! note "* Autocompletion"!!! note "* Auto completion" For the autocompletion to work on all shells you also need to add the dependency `click-completion`.
Just that. And **Typer** does the rest. If **Typer** detects `click-completion` installed, it will automatically create 2 *CLI options*:
* `--install-completion`: Install completion for the current shell. * `--show-completion`: Show completion for the current shell, to copy it or customize the installation.
Then you can tell the user to run that command and the rest will just work.
It works when you create a package (installable with `pip`). Or when using [Typer CLI](typer-cli.md){.internal-link target=_blank}.
## The power of Click
<a href="https://click.palletsprojects.com" class="external-link" target="_blank">Click</a> is one of the most popular tools for building CLIs in Python.
13 unmodified linesmodified:docs/index.md+6 added-3 removed
32 unmodified lines33 * **Intuitive to write**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.34 * **Easy to use**: It's easy to use for the final users. Automatic help, and (optional) automatic completion for all shells.35 * **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.36 * **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.37-* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups subcommands, with options and arguments.37+* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.38 39 ## Requirements40 41 Python 3.6+55 unmodified lines97 --install-completion Install completion for the current shell.98 --show-completion Show completion for the current shell, to copy it or customize the installation.99 --help Show this message and exit.100 101-// You get ✨ auto completion ✨ for free, installed with --install-completion101+// When you create a package you get ✨ auto completion ✨ for free, installed with --install-completion102 103 // Now pass the NAME argument104 $ python main.py Camila105 3 unmodified lines109 ```110 111 </div>112 113+**Note**: Auto completion works when you create a Python package and run it with `--install-completion` or when you use <a href="https://typer.tiangolo.com/typer-cli/" class="internal-link" target="_blank">Typer CLI</a>.114+115 ## Example upgrade116 117 This was the simplest example possible.118 123 unmodified lines242 And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.243 244 **You get**: great editor support, including **completion** and **type checks** everywhere.245 244-**Your users get**: automatic **`--help`**, (optional) **autocompletion** in their terminal (Bash, Zsh, Fish, PowerShell).246+**Your users get**: automatic **`--help`**, (optional) **auto completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using <a href="https://typer.tiangolo.com/typer-cli/" class="internal-link" target="_blank">Typer CLI</a>.247 248 For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.249 250 ## Optional Dependencies17 unmodified lines268 269 * <a href="https://github.com/click-contrib/click-spinner" class="external-link" target="_blank"><code>click-spinner</code></a>: to show the user that you are loading data. A Click plug-in.270 * There are several other Click plug-ins at <a href="https://github.com/click-contrib" class="external-link" target="_blank">click-contrib</a> that you can explore.271 * <a href="https://pypi.org/project/tabulate/" class="external-link" target="_blank"><code>tabulate</code></a>: to automatically display tabular data nicely. Independent of Click or typer.272+* <a href="https://github.com/tqdm/tqdm" class="external-link" target="_blank"><code>tqdm</code></a>: a fast, extensible progress bar, alternative to Typer's own `typer.progressbar()`.273 * etc... you can re-use many of the great available tools for building CLIs.274 275 ## License276 1 unmodified lineadded:docs/typer-cli.md+431 added
1+# Typer CLI2+3+<p align="center">4+ <em>Run <strong>Typer</strong> scripts with completion, without having to create a package, using <strong>Typer CLI</strong>.</em>5+</p>6+<p align="center">7+<a href="https://travis-ci.com/tiangolo/typer-cli" target="_blank">8+ <img src="https://travis-ci.com/tiangolo/typer-cli.svg?branch=master" alt="Build Status">9+</a>10+<a href="https://codecov.io/gh/tiangolo/typer-cli" target="_blank">11+ <img src="https://codecov.io/gh/tiangolo/typer-cli/branch/master/graph/badge.svg" alt="Coverage">12+</a>13+<a href="https://pypi.org/project/typer-cli" target="_blank">14+ <img src="https://badge.fury.io/py/typer-cli.svg" alt="Package version">15+</a>16+</p>17+18+There is an optional utility tool called **Typer CLI**, additional to **Typer** itself.19+20+It's main feature is to provide ✨ completion ✨ in the Terminal for your own small programs built with **Typer**.21+22+...without you having to create a complete installable Python package.23+24+It's probably most useful if you have a small custom Python script using **Typer** (maybe as part of some project), for some small tasks, and it's not complex/important enough to create a whole installable Python package for it (something to be installed with `pip`).25+26+In that case, you can install **Typer CLI**, and run your program with the `typer` command in your Terminal, and it will provide completion for your script.27+28+You can also use **Typer CLI** to generate Markdown documentation for your own **Typer** programs 📝.29+30+---31+32+**Documentation**: <a href="https://typer.tiangolo.com/typer-cli/" target="_blank">https://typer.tiangolo.com/typer-cli/</a>33+34+**Source Code for Typer CLI**: <a href="https://github.com/tiangolo/typer-cli" target="_blank">https://github.com/tiangolo/typer-cli</a>35+36+---37+38+## **Typer** or **Typer CLI**39+40+**Typer** is a library for building CLIs (Command Line Interface applications).41+42+You use **Typer** in your Python scripts. Like in:43+44+```Python45+import typer46+47+48+def main():49+ typer.echo("Hello World")50+51+52+if __name__ == "__main__":53+ typer.run(main)54+```55+56+**Typer CLI** is a command line application to run simple programs created with **Typer**, with completion in your terminal 🚀.57+58+You use **Typer CLI** in your terminal, to run your scripts (as an alternative to calling `python` directly). Like in:59+60+<div class="termy">61+62+```console63+$ typer my_script.py run64+65+Hello World66+```67+68+</div>69+70+But you never import anything from **Typer CLI** in your own scripts.71+72+## Usage73+74+### Install75+76+Install **Typer CLI**:77+78+<div class="termy">79+80+```console81+$ python -m pip install typer-cli82+---> 100%83+Successfully installed typer-cli84+```85+86+</div>87+88+That creates a `typer` command you can call in your terminal, much like `python`, `git`, or `echo`.89+90+You can then install completion for it:91+92+<div class="termy">93+94+```console95+$ typer --install-completion96+97+zsh completion installed in /home/user/.bashrc.98+Completion will take effect once you restart the terminal.99+```100+101+</div>102+103+### Sample script104+105+Let's say you have a script that uses **Typer** in `my_custom_script.py`:106+107+```Python108+import typer109+110+app = typer.Typer()111+112+113+@app.command()114+def hello(name: str = None):115+ if name:116+ typer.echo(f"Hello {name}")117+ else:118+ typer.echo("Hello World!")119+120+121+@app.command()122+def bye(name: str = None):123+ if name:124+ typer.echo(f"Bye {name}")125+ else:126+ typer.echo("Goodbye!")127+128+129+if __name__ == "__main__":130+ app()131+```132+133+For it to work, you would also install **Typer**:134+135+<div class="termy">136+137+```console138+$ python -m pip install typer139+---> 100%140+Successfully installed typer141+```142+143+</div>144+145+### Run with Python146+147+Then you could run your script with normal Python:148+149+<div class="termy">150+151+```console152+$ python my_custom_script.py hello153+154+Hello World!155+156+$ python my_custom_script.py hello --name Camila157+158+Hello Camila!159+160+$ python my_custom_script.py bye --name Camila161+162+Bye Camila163+```164+165+</div>166+167+There's nothing wrong with using Python directly to run it. And, in fact, if some other code or program uses your script, that would probably be the best way to do it.168+169+⛔️ But in your terminal, you won't get completion when hitting <kbd>TAB</kbd> for any of the subcommands or options, like `hello`, `bye`, and `--name`.170+171+### Run with **Typer CLI**172+173+Here's where **Typer CLI** is useful.174+175+You can also run the same script with the `typer` command you get after installing `typer-cli`:176+177+<div class="termy">178+179+```console180+$ typer my_custom_script.py run hello181+182+Hello World!183+184+$ typer my_custom_script.py run hello --name Camila185+186+Hello Camila!187+188+$ typer my_custom_script.py run bye --name Camila189+190+Bye Camila191+```192+193+</div>194+195+* Instead of using `python` directly you use the `typer` command.196+* After the name of the file, add the subcommand `run`.197+198+✔️ If you installed completion for **Typer CLI** (for the `typer` command) as described above, when you hit <kbd>TAB</kbd> you will have ✨ completion for everything ✨, including all the subcommands and options of your script, like `hello`, `bye`, and `--name` 🚀.199+200+## If main201+202+Because **Typer CLI** won't use the block with:203+204+```Python205+if __name__ == "__main__":206+ app()207+```208+209+...you can also remove it if you are calling that script only with **Typer CLI** (using the `typer` command).210+211+## Run other files212+213+**Typer CLI** can run any script with **Typer**, but the script doesn't even have to use **Typer** at all.214+215+**Typer CLI** could even run a file with a function that could be used with `typer.run()`, even if the script doesn't use `typer.run()` or anything else.216+217+For example, a file `main.py` like this will still work:218+219+```Python220+def main(name: str = "World"):221+ """222+ Say hi to someone, by default to the World.223+ """224+ print(f"Hello {name}")225+```226+227+Then you can call it with:228+229+<div class="termy">230+231+```console232+$ typer main.py run --help233+Usage: typer run [OPTIONS]234+235+ Say hi to someone, by default to the World.236+237+Options:238+ --name TEXT239+ --help Show this message and exit.240+241+$ typer main.py run --name Camila242+243+Hello Camila244+```245+246+</div>247+248+And it will also have completion for things like the `--name` *CLI Option*.249+250+## Run a package or module251+252+Instead of a file path you can pass a module (possibly in a package) to import.253+254+For example:255+256+<div class="termy">257+258+```console259+$ typer my_package.main run --help260+Usage: typer run [OPTIONS]261+262+Options:263+ --name TEXT264+ --help Show this message and exit.265+266+$ typer my_package.main run --name Camila267+268+Hello Camila269+```270+271+</div>272+273+## Options274+275+You can specify one of the following **CLI Options**:276+277+* `--app`: the name of the variable with a `Typer()` object to run as the main app.278+* `--func`: the name of the variable with a function that would be used with `typer.run()`.279+280+### Defaults281+282+When your run a script with the **Typer CLI** (the `typer` command) it will use the app from the following priority:283+284+* An app object from the `--app` *CLI Option*.285+* A function to convert to a **Typer** app from `--func` *CLI Option* (like when using `typer.run()`).286+* A **Typer** app in a variable with a name of `app`, `cli`, or `main`.287+* The first **Typer** app available in the file, with any name.288+* A function in a variable with a name of `main`, `cli`, or `app`.289+* The first function in the file, with any name.290+291+## Generate docs292+293+**Typer CLI** can also generate Markdown documentation for your **Typer** application.294+295+### Sample script with docs296+297+For example, you could have a script like:298+299+```Python300+{!./src/commands/help/tutorial001.py!}301+```302+303+### Generate docs with Typer CLI304+305+Then you could generate docs for it with **Typer CLI**.306+307+You can use the subcommand `utils`.308+309+And then the subcommand `docs`.310+311+<div class="termy">312+313+```console314+$ typer some_script.py utils docs315+```316+317+</div>318+319+**Options**:320+321+* `--name TEXT`: The name of the CLI program to use in docs.322+* `--output FILE`: An output file to write docs to, like README.md.323+324+For example:325+326+<div class="termy">327+328+```console329+$ typer my_package.main utils docs --name awesome-cli --output README.md330+331+Docs saved to: README.md332+```333+334+</div>335+336+### Sample docs output337+338+For example, for the previous script, the generated docs would look like:339+340+---341+342+## `awesome-cli`343+344+Awesome CLI user manager.345+346+**Usage**:347+348+```console349+$ awesome-cli [OPTIONS] COMMAND [ARGS]...350+```351+352+**Options**:353+354+* `--install-completion`: Install completion for the current shell.355+* `--show-completion`: Show completion for the current shell, to copy it or customize the installation.356+* `--help`: Show this message and exit.357+358+**Commands**:359+360+* `create`: Create a new user with USERNAME.361+* `delete`: Delete a user with USERNAME.362+* `delete-all`: Delete ALL users in the database.363+* `init`: Initialize the users database.364+365+## `awesome-cli create`366+367+Create a new user with USERNAME.368+369+**Usage**:370+371+```console372+$ awesome-cli create [OPTIONS] USERNAME373+```374+375+**Options**:376+377+* `--help`: Show this message and exit.378+379+## `awesome-cli delete`380+381+Delete a user with USERNAME.382+383+If --force is not used, will ask for confirmation.384+385+**Usage**:386+387+```console388+$ awesome-cli delete [OPTIONS] USERNAME389+```390+391+**Options**:392+393+* `--force / --no-force`: Force deletion without confirmation. [required]394+* `--help`: Show this message and exit.395+396+## `awesome-cli delete-all`397+398+Delete ALL users in the database.399+400+If --force is not used, will ask for confirmation.401+402+**Usage**:403+404+```console405+$ awesome-cli delete-all [OPTIONS]406+```407+408+**Options**:409+410+* `--force / --no-force`: Force deletion without confirmation. [required]411+* `--help`: Show this message and exit.412+413+## `awesome-cli init`414+415+Initialize the users database.416+417+**Usage**:418+419+```console420+$ awesome-cli init [OPTIONS]421+```422+423+**Options**:424+425+* `--help`: Show this message and exit.426+427+---428+429+## License430+431+**Typer CLI**, the same as **Typer**, is licensed under the terms of the MIT license.modified:scripts/test.sh+2 added-3 removed
1234567891091011#!/usr/bin/env bash
set -eset -x
bash ./scripts/test-files.shbash ./scripts/lint.shexport PYTHONPATH=./docs/src# Use xdist-pytest --forked to ensure modified sys.path to import relative modules in examples keeps workingpytest --cov=typer --cov=tests --cov=docs/src --cov-report=term-missing -o console_output_style=progress --forked --numprocesses=auto ${@}bash ./scripts/lint.sh# Include tests for filesbash ./scripts/test-files.shmodified:mkdocs.yml+1 added
63 unmodified lines64 - Ask with Prompt: 'tutorial/prompt.md'65 - Progress Bar: 'tutorial/progressbar.md'66 - CLI Application Directory: 'tutorial/app-dir.md'67 - Launching Applications: 'tutorial/launch.md'68+ - Typer CLI - completion for small scripts: 'typer-cli.md'69 - Alternatives, Inspiration and Comparisons: 'alternatives.md'70 - Help Typer - Get Help: 'help-typer.md'71 - Development - Contributing: 'contributing.md'72 - Release Notes: release-notes.md40 unmodified linesmodified:README.md+6 added-3 removed
32 unmodified lines33 * **Intuitive to write**: Great editor support. <abbr title="also known as auto-complete, autocompletion, IntelliSense">Completion</abbr> everywhere. Less time debugging. Designed to be easy to use and learn. Less time reading docs.34 * **Easy to use**: It's easy to use for the final users. Automatic help, and (optional) automatic completion for all shells.35 * **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.36 * **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.37-* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups subcommands, with options and arguments.37+* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.38 39 ## Requirements40 41 Python 3.6+55 unmodified lines97 --install-completion Install completion for the current shell.98 --show-completion Show completion for the current shell, to copy it or customize the installation.99 --help Show this message and exit.100 101-// You get ✨ auto completion ✨ for free, installed with --install-completion101+// When you create a package you get ✨ auto completion ✨ for free, installed with --install-completion102 103 // Now pass the NAME argument104 $ python main.py Camila105 3 unmodified lines109 ```110 111 </div>112 113+**Note**: Auto completion works when you create a Python package and run it with `--install-completion` or when you use <a href="https://typer.tiangolo.com/typer-cli/" class="internal-link" target="_blank">Typer CLI</a>.114+115 ## Example upgrade116 117 This was the simplest example possible.118 123 unmodified lines242 And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.243 244 **You get**: great editor support, including **completion** and **type checks** everywhere.245 244-**Your users get**: automatic **`--help`**, (optional) **autocompletion** in their terminal (Bash, Zsh, Fish, PowerShell).246+**Your users get**: automatic **`--help`**, (optional) **auto completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using <a href="https://typer.tiangolo.com/typer-cli/" class="internal-link" target="_blank">Typer CLI</a>.247 248 For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.249 250 ## Optional Dependencies17 unmodified lines268 269 * <a href="https://github.com/click-contrib/click-spinner" class="external-link" target="_blank"><code>click-spinner</code></a>: to show the user that you are loading data. A Click plug-in.270 * There are several other Click plug-ins at <a href="https://github.com/click-contrib" class="external-link" target="_blank">click-contrib</a> that you can explore.271 * <a href="https://pypi.org/project/tabulate/" class="external-link" target="_blank"><code>tabulate</code></a>: to automatically display tabular data nicely. Independent of Click or typer.272+* <a href="https://github.com/tqdm/tqdm" class="external-link" target="_blank"><code>tqdm</code></a>: a fast, extensible progress bar, alternative to Typer's own `typer.progressbar()`.273 * etc... you can re-use many of the great available tools for building CLIs.274 275 ## License276 1 unmodified line