typer-cli.md
This file
Path
docs/typer-cli.md
433 lines · 9.5 KiB · Markdown
Last changed by
Not known.
History of this fileTake it
The walk stopped after 200 commits: lines older than d5223d6 point at it.
✏ Fix syntax typo in `docs/tutorial/package.md` (#333)Ryan Streurbefore adoptiond5223d6
lines 1–433why, one step back1# Typer CLI23<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://img.shields.io/codecov/c/github/tiangolo/typer-cli" 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>1718There is an optional utility tool called **Typer CLI**, additional to **Typer** itself.1920It's main feature is to provide ✨ completion ✨ in the Terminal for your own small programs built with **Typer**.2122...without you having to create a complete installable Python package.2324It'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`).2526In 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.2728You can also use **Typer CLI** to generate Markdown documentation for your own **Typer** programs 📝.2930---3132**Documentation**: <a href="https://typer.tiangolo.com/typer-cli/" target="_blank">https://typer.tiangolo.com/typer-cli/</a>3334**Source Code for Typer CLI**: <a href="https://github.com/tiangolo/typer-cli" target="_blank">https://github.com/tiangolo/typer-cli</a>3536---3738## **Typer** or **Typer CLI**3940**Typer** is a library for building CLIs (Command Line Interface applications).4142You use **Typer** in your Python scripts. Like in:4344```Python45import typer464748def main():49 typer.echo("Hello World")505152if __name__ == "__main__":53 typer.run(main)54```5556**Typer CLI** is a command line application to run simple programs created with **Typer**, with completion in your terminal 🚀.5758You use **Typer CLI** in your terminal, to run your scripts (as an alternative to calling `python` directly). Like in:5960<div class="termy">6162```console63$ typer my_script.py run6465Hello World66```6768</div>6970But you never import anything from **Typer CLI** in your own scripts.7172## Usage7374### Install7576Install **Typer CLI**:7778<div class="termy">7980```console81$ python -m pip install typer-cli82---> 100%83Successfully installed typer-cli84```8586</div>8788That creates a `typer` command you can call in your terminal, much like `python`, `git`, or `echo`.8990You can then install completion for it:9192<div class="termy">9394```console95$ typer --install-completion9697zsh completion installed in /home/user/.bashrc.98Completion will take effect once you restart the terminal.99```100101</div>102103### Sample script104105Let's say you have a script that uses **Typer** in `my_custom_script.py`:106107```Python108from typing import Optional109110import typer111112app = typer.Typer()113114115@app.command()116def hello(name: Optional[str] = None):117 if name:118 typer.echo(f"Hello {name}")119 else:120 typer.echo("Hello World!")121122123@app.command()124def bye(name: Optional[str] = None):125 if name:126 typer.echo(f"Bye {name}")127 else:128 typer.echo("Goodbye!")129130131if __name__ == "__main__":132 app()133```134135For it to work, you would also install **Typer**:136137<div class="termy">138139```console140$ python -m pip install typer141---> 100%142Successfully installed typer143```144145</div>146147### Run with Python148149Then you could run your script with normal Python:150151<div class="termy">152153```console154$ python my_custom_script.py hello155156Hello World!157158$ python my_custom_script.py hello --name Camila159160Hello Camila!161162$ python my_custom_script.py bye --name Camila163164Bye Camila165```166167</div>168169There'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.170171⛔️ 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`.172173### Run with **Typer CLI**174175Here's where **Typer CLI** is useful.176177You can also run the same script with the `typer` command you get after installing `typer-cli`:178179<div class="termy">180181```console182$ typer my_custom_script.py run hello183184Hello World!185186$ typer my_custom_script.py run hello --name Camila187188Hello Camila!189190$ typer my_custom_script.py run bye --name Camila191192Bye Camila193```194195</div>196197* Instead of using `python` directly you use the `typer` command.198* After the name of the file, add the subcommand `run`.199200✔️ 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` 🚀.201202## If main203204Because **Typer CLI** won't use the block with:205206```Python207if __name__ == "__main__":208 app()209```210211...you can also remove it if you are calling that script only with **Typer CLI** (using the `typer` command).212213## Run other files214215**Typer CLI** can run any script with **Typer**, but the script doesn't even have to use **Typer** at all.216217**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.218219For example, a file `main.py` like this will still work:220221```Python222def main(name: str = "World"):223 """224 Say hi to someone, by default to the World.225 """226 print(f"Hello {name}")227```228229Then you can call it with:230231<div class="termy">232233```console234$ typer main.py run --help235Usage: typer run [OPTIONS]236237 Say hi to someone, by default to the World.238239Options:240 --name TEXT241 --help Show this message and exit.242243$ typer main.py run --name Camila244245Hello Camila246```247248</div>249250And it will also have completion for things like the `--name` *CLI Option*.251252## Run a package or module253254Instead of a file path you can pass a module (possibly in a package) to import.255256For example:257258<div class="termy">259260```console261$ typer my_package.main run --help262Usage: typer run [OPTIONS]263264Options:265 --name TEXT266 --help Show this message and exit.267268$ typer my_package.main run --name Camila269270Hello Camila271```272273</div>274275## Options276277You can specify one of the following **CLI options**:278279* `--app`: the name of the variable with a `Typer()` object to run as the main app.280* `--func`: the name of the variable with a function that would be used with `typer.run()`.281282### Defaults283284When your run a script with the **Typer CLI** (the `typer` command) it will use the app from the following priority:285286* An app object from the `--app` *CLI Option*.287* A function to convert to a **Typer** app from `--func` *CLI Option* (like when using `typer.run()`).288* A **Typer** app in a variable with a name of `app`, `cli`, or `main`.289* The first **Typer** app available in the file, with any name.290* A function in a variable with a name of `main`, `cli`, or `app`.291* The first function in the file, with any name.292293## Generate docs294295**Typer CLI** can also generate Markdown documentation for your **Typer** application.296297### Sample script with docs298299For example, you could have a script like:300301```Python302{!../docs_src/commands/help/tutorial001.py!}303```304305### Generate docs with Typer CLI306307Then you could generate docs for it with **Typer CLI**.308309You can use the subcommand `utils`.310311And then the subcommand `docs`.312313<div class="termy">314315```console316$ typer some_script.py utils docs317```318319</div>320321**Options**:322323* `--name TEXT`: The name of the CLI program to use in docs.324* `--output FILE`: An output file to write docs to, like README.md.325326For example:327328<div class="termy">329330```console331$ typer my_package.main utils docs --name awesome-cli --output README.md332333Docs saved to: README.md334```335336</div>337338### Sample docs output339340For example, for the previous script, the generated docs would look like:341342---343344## `awesome-cli`345346Awesome CLI user manager.347348**Usage**:349350```console351$ awesome-cli [OPTIONS] COMMAND [ARGS]...352```353354**Options**:355356* `--install-completion`: Install completion for the current shell.357* `--show-completion`: Show completion for the current shell, to copy it or customize the installation.358* `--help`: Show this message and exit.359360**Commands**:361362* `create`: Create a new user with USERNAME.363* `delete`: Delete a user with USERNAME.364* `delete-all`: Delete ALL users in the database.365* `init`: Initialize the users database.366367## `awesome-cli create`368369Create a new user with USERNAME.370371**Usage**:372373```console374$ awesome-cli create [OPTIONS] USERNAME375```376377**Options**:378379* `--help`: Show this message and exit.380381## `awesome-cli delete`382383Delete a user with USERNAME.384385If --force is not used, will ask for confirmation.386387**Usage**:388389```console390$ awesome-cli delete [OPTIONS] USERNAME391```392393**Options**:394395* `--force / --no-force`: Force deletion without confirmation. [required]396* `--help`: Show this message and exit.397398## `awesome-cli delete-all`399400Delete ALL users in the database.401402If --force is not used, will ask for confirmation.403404**Usage**:405406```console407$ awesome-cli delete-all [OPTIONS]408```409410**Options**:411412* `--force / --no-force`: Force deletion without confirmation. [required]413* `--help`: Show this message and exit.414415## `awesome-cli init`416417Initialize the users database.418419**Usage**:420421```console422$ awesome-cli init [OPTIONS]423```424425**Options**:426427* `--help`: Show this message and exit.428429---430431## License432433**Typer CLI**, the same as **Typer**, is licensed under the terms of the MIT license.