Skip to content
Myr

README.md

This file

Path

README.md

386 lines · 14.0 KiB · Markdown

Last changed by

🩺 Update test badge to only reflect pushes to `master` (#1414)Sofie Van Landeghembefore adoptioncc416ba

History of this file

Take it

The walk stopped after 200 commits: lines older than 50b1018 point at it.

🔖 Release version 0.17.1Sebastián Ramírezbefore adoption50b1018

lines 1–8why, one step back
1<p align="center">
2 <a href="https://typer.tiangolo.com"><img src="https://typer.tiangolo.com/img/logo-margin/logo-margin-vector.svg#only-light" alt="Typer"></a>34</p>5<p align="center">6 <em>Typer, build great CLIs. Easy to code. Based on Python type hints.</em>7</p>8<p align="center">

🩺 Update test badge to only reflect pushes to `master` (#1414)Sofie Van Landeghembefore adoptioncc416ba

lines 9–10why, one step back
9<a href="https://github.com/fastapi/typer/actions?query=workflow%3ATest+event%3Apush+branch%3Amaster" target="_blank">
10 <img src="https://github.com/fastapi/typer/actions/workflows/test.yml/badge.svg?event=push&branch=master" alt="Test">

🔖 Release version 0.17.1Sebastián Ramírezbefore adoption50b1018

lines 11–320why, one step back
11</a>
12<a href="https://github.com/fastapi/typer/actions?query=workflow%3APublish" target="_blank">13 <img src="https://github.com/fastapi/typer/workflows/Publish/badge.svg" alt="Publish">14</a>15<a href="https://coverage-badge.samuelcolvin.workers.dev/redirect/fastapi/typer" target="_blank">16 <img src="https://coverage-badge.samuelcolvin.workers.dev/fastapi/typer.svg" alt="Coverage">17<a href="https://pypi.org/project/typer" target="_blank">18 <img src="https://img.shields.io/pypi/v/typer?color=%2334D058&label=pypi%20package" alt="Package version">19</a>20</p>2122---2324**Documentation**: <a href="https://typer.tiangolo.com" target="_blank">https://typer.tiangolo.com</a>2526**Source Code**: <a href="https://github.com/fastapi/typer" target="_blank">https://github.com/fastapi/typer</a>2728---2930Typer is a library for building <abbr title="command line interface, programs executed from a terminal">CLI</abbr> applications that users will **love using** and developers will **love creating**. Based on Python type hints.3132It's also a command line tool to run scripts, automatically converting them to CLI applications.3334The key features are:3536* **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.37* **Easy to use**: It's easy to use for the final users. Automatic help, and automatic completion for all shells.38* **Short**: Minimize code duplication. Multiple features from each parameter declaration. Fewer bugs.39* **Start simple**: The simplest example adds only 2 lines of code to your app: **1 import, 1 function call**.40* **Grow large**: Grow in complexity as much as you want, create arbitrarily complex trees of commands and groups of subcommands, with options and arguments.41* **Run scripts**: Typer includes a `typer` command/program that you can use to run scripts, automatically converting them to CLIs, even if they don't use Typer internally.4243## FastAPI of CLIs4445**Typer** is <a href="https://fastapi.tiangolo.com" class="external-link" target="_blank">FastAPI</a>'s little sibling, it's the FastAPI of CLIs.4647## Installation4849Create and activate a <a href="https://typer.tiangolo.com/virtual-environments/" class="external-link" target="_blank">virtual environment</a> and then install **Typer**:5051<div class="termy">5253```console54$ pip install typer55---> 100%56Successfully installed typer rich shellingham57```5859</div>6061## Example6263### The absolute minimum6465* Create a file `main.py` with:6667```Python68def main(name: str):69 print(f"Hello {name}")70```7172This script doesn't even use Typer internally. But you can use the `typer` command to run it as a CLI application.7374### Run it7576Run your application with the `typer` command:7778<div class="termy">7980```console81// Run your application82$ typer main.py run8384// You get a nice error, you are missing NAME85Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME86Try 'typer [PATH_OR_MODULE] run --help' for help.87╭─ Error ───────────────────────────────────────────╮88│ Missing argument 'NAME'. │89╰───────────────────────────────────────────────────╯909192// You get a --help for free93$ typer main.py run --help9495Usage: typer [PATH_OR_MODULE] run [OPTIONS] NAME9697Run the provided Typer app.9899╭─ Arguments ───────────────────────────────────────╮100│ * name TEXT [default: None] [required] |101╰───────────────────────────────────────────────────╯102╭─ Options ─────────────────────────────────────────╮103│ --help Show this message and exit. │104╰───────────────────────────────────────────────────╯105106// Now pass the NAME argument107$ typer main.py run Camila108109Hello Camila110111// It works! 🎉112```113114</div>115116This is the simplest use case, not even using Typer internally, but it can already be quite useful for simple scripts.117118**Note**: auto-completion works when you create a Python package and run it with `--install-completion` or when you use the `typer` command.119120## Use Typer in your code121122Now let's start using Typer in your own code, update `main.py` with:123124```Python125import typer126127128def main(name: str):129 print(f"Hello {name}")130131132if __name__ == "__main__":133 typer.run(main)134```135136Now you could run it with Python directly:137138<div class="termy">139140```console141// Run your application142$ python main.py143144// You get a nice error, you are missing NAME145Usage: main.py [OPTIONS] NAME146Try 'main.py --help' for help.147╭─ Error ───────────────────────────────────────────╮148│ Missing argument 'NAME'. │149╰───────────────────────────────────────────────────╯150151152// You get a --help for free153$ python main.py --help154155Usage: main.py [OPTIONS] NAME156157╭─ Arguments ───────────────────────────────────────╮158│ * name TEXT [default: None] [required] |159╰───────────────────────────────────────────────────╯160╭─ Options ─────────────────────────────────────────╮161│ --help Show this message and exit. │162╰───────────────────────────────────────────────────╯163164// Now pass the NAME argument165$ python main.py Camila166167Hello Camila168169// It works! 🎉170```171172</div>173174**Note**: you can also call this same script with the `typer` command, but you don't need to.175176## Example upgrade177178This was the simplest example possible.179180Now let's see one a bit more complex.181182### An example with two subcommands183184Modify the file `main.py`.185186Create a `typer.Typer()` app, and create two subcommands with their parameters.187188```Python hl_lines="3 6 11 20"189import typer190191app = typer.Typer()192193194@app.command()195def hello(name: str):196 print(f"Hello {name}")197198199@app.command()200def goodbye(name: str, formal: bool = False):201 if formal:202 print(f"Goodbye Ms. {name}. Have a good day.")203 else:204 print(f"Bye {name}!")205206207if __name__ == "__main__":208 app()209```210211And that will:212213* Explicitly create a `typer.Typer` app.214 * The previous `typer.run` actually creates one implicitly for you.215* Add two subcommands with `@app.command()`.216* Execute the `app()` itself, as if it was a function (instead of `typer.run`).217218### Run the upgraded example219220Check the new help:221222<div class="termy">223224```console225$ python main.py --help226227 Usage: main.py [OPTIONS] COMMAND [ARGS]...228229╭─ Options ─────────────────────────────────────────╮230│ --install-completion Install completion │231│ for the current │232│ shell. │233│ --show-completion Show completion for │234│ the current shell, │235│ to copy it or │236│ customize the │237│ installation. │238│ --help Show this message │239│ and exit. │240╰───────────────────────────────────────────────────╯241╭─ Commands ────────────────────────────────────────╮242│ goodbye │243│ hello │244╰───────────────────────────────────────────────────╯245246// When you create a package you get ✨ auto-completion ✨ for free, installed with --install-completion247248// You have 2 subcommands (the 2 functions): goodbye and hello249```250251</div>252253Now check the help for the `hello` command:254255<div class="termy">256257```console258$ python main.py hello --help259260 Usage: main.py hello [OPTIONS] NAME261262╭─ Arguments ───────────────────────────────────────╮263│ * name TEXT [default: None] [required] │264╰───────────────────────────────────────────────────╯265╭─ Options ─────────────────────────────────────────╮266│ --help Show this message and exit. │267╰───────────────────────────────────────────────────╯268```269270</div>271272And now check the help for the `goodbye` command:273274<div class="termy">275276```console277$ python main.py goodbye --help278279 Usage: main.py goodbye [OPTIONS] NAME280281╭─ Arguments ───────────────────────────────────────╮282│ * name TEXT [default: None] [required] │283╰───────────────────────────────────────────────────╯284╭─ Options ─────────────────────────────────────────╮285│ --formal --no-formal [default: no-formal] │286│ --help Show this message │287│ and exit. │288╰───────────────────────────────────────────────────╯289290// Automatic --formal and --no-formal for the bool option 🎉291```292293</div>294295Now you can try out the new command line application:296297<div class="termy">298299```console300// Use it with the hello command301302$ python main.py hello Camila303304Hello Camila305306// And with the goodbye command307308$ python main.py goodbye Camila309310Bye Camila!311312// And with --formal313314$ python main.py goodbye --formal Camila315316Goodbye Ms. Camila. Have a good day.317```318319</div>320

📝 Clarify single-command vs multi-command behaviour in README (#1268)Morgen Pronkbefore adoptione4c28a4

lines 321–322why, one step back
321**Note**: If your app only has one command, by default the command name is **omitted** in usage: `python main.py Camila`. However, when there are multiple commands, you must **explicitly include the command name**: `python main.py hello Camila`. See [One or Multiple Commands](https://typer.tiangolo.com/tutorial/commands/one-or-multiple/) for more details.
322

🔖 Release version 0.17.1Sebastián Ramírezbefore adoption50b1018

lines 323–386why, one step back
323### Recap
324325In summary, you declare **once** the types of parameters (*CLI arguments* and *CLI options*) as function parameters.326327You do that with standard modern Python types.328329You don't have to learn a new syntax, the methods or classes of a specific library, etc.330331Just standard **Python**.332333For example, for an `int`:334335```Python336total: int337```338339or for a `bool` flag:340341```Python342force: bool343```344345And similarly for **files**, **paths**, **enums** (choices), etc. And there are tools to create **groups of subcommands**, add metadata, extra **validation**, etc.346347**You get**: great editor support, including **completion** and **type checks** everywhere.348349**Your users get**: automatic **`--help`**, **auto-completion** in their terminal (Bash, Zsh, Fish, PowerShell) when they install your package or when using the `typer` command.350351For a more complete example including more features, see the <a href="https://typer.tiangolo.com/tutorial/">Tutorial - User Guide</a>.352353## Dependencies354355**Typer** stands on the shoulders of a giant. Its only internal required dependency is <a href="https://click.palletsprojects.com/" class="external-link" target="_blank">Click</a>.356357By default it also comes with extra standard dependencies:358359* <a href="https://rich.readthedocs.io/en/stable/index.html" class="external-link" target="_blank"><code>rich</code></a>: to show nicely formatted errors automatically.360* <a href="https://github.com/sarugaku/shellingham" class="external-link" target="_blank"><code>shellingham</code></a>: to automatically detect the current shell when installing completion.361 * With `shellingham` you can just use `--install-completion`.362 * Without `shellingham`, you have to pass the name of the shell to install completion for, e.g. `--install-completion bash`.363364### `typer-slim`365366If you don't want the extra standard optional dependencies, install `typer-slim` instead.367368When you install with:369370```bash371pip install typer372```373374...it includes the same code and dependencies as:375376```bash377pip install "typer-slim[standard]"378```379380The `standard` extra dependencies are `rich` and `shellingham`.381382**Note**: The `typer` command is only included in the `typer` package.383384## License385386This project is licensed under the terms of the MIT license.