:memo: Add docs and examples for Commands
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Sebastián Ramírez · committed by Sebastián Ramírez · parent 57b3cc1 · Browse files · 8 files·+719 added−0 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+719 added−0 removed
- other:+719 added−0 removed
Provenance
- Commit
b883516- Tree
2c73ed6- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
Sebastián Ramírez <tiangolo@gmail.com>- Parent
57b3cc1
8 files changed+719 added−0 removed
added:docs/src/commands/tutorial001.py+12 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def main(name: str):8+ typer.echo(f"Hello {name}")9+10+11+if __name__ == "__main__":12+ app()added:docs/src/commands/tutorial002.py+17 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create():8+ typer.echo("Creating user: Hiro Hamada")9+10+11+@app.command()12+def delete():13+ typer.echo("Deleting user: Hiro Hamada")14+15+16+if __name__ == "__main__":17+ app()added:docs/src/commands/tutorial003.py+17 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create(username: str):8+ typer.echo(f"Creating user: {username}")9+10+11+@app.command()12+def delete(username: str):13+ typer.echo(f"Deleting user: {username}")14+15+16+if __name__ == "__main__":17+ app()added:docs/src/commands/tutorial004.py+38 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command()7+def create(username: str):8+ typer.echo(f"Creating user: {username}")9+10+11+@app.command()12+def delete(13+ username: str,14+ force: bool = typer.Option(..., prompt="Are you sure you want to delete the user?"),15+):16+ if force:17+ typer.echo(f"Deleting user: {username}")18+ else:19+ typer.echo("Operation cancelled")20+21+22+@app.command()23+def delete_all(24+ force: bool = typer.Option(..., prompt="Are you sure you want to delete ALL users?")25+):26+ if force:27+ typer.echo("Deleting all users")28+ else:29+ typer.echo("Operation cancelled")30+31+32+@app.command()33+def init():34+ typer.echo("Initializing user database")35+36+37+if __name__ == "__main__":38+ app()added:docs/src/commands/tutorial005.py+62 added
1+import typer2+3+app = typer.Typer(help="Awesome CLI user manager.")4+5+6+@app.command()7+def create(username: str):8+ """9+ Create a new user with USERNAME.10+ """11+ typer.echo(f"Creating user: {username}")12+13+14+@app.command()15+def delete(16+ username: str,17+ force: bool = typer.Option(18+ ...,19+ prompt="Are you sure you want to delete the user?",20+ help="Force deletion without confirmation.",21+ ),22+):23+ """24+ Delete a user with USERNAME.25+26+ If --force is not used, will ask for confirmation.27+ """28+ if force:29+ typer.echo(f"Deleting user: {username}")30+ else:31+ typer.echo("Operation cancelled")32+33+34+@app.command()35+def delete_all(36+ force: bool = typer.Option(37+ ...,38+ prompt="Are you sure you want to delete ALL users?",39+ help="Force deletion without confirmation.",40+ )41+):42+ """43+ Delete ALL users in the database.44+45+ If --force is not used, will ask for confirmation.46+ """47+ if force:48+ typer.echo("Deleting all users")49+ else:50+ typer.echo("Operation cancelled")51+52+53+@app.command()54+def init():55+ """56+ Initialize the users database.57+ """58+ typer.echo("Initializing user database")59+60+61+if __name__ == "__main__":62+ app()added:docs/src/commands/tutorial006.py+17 added
1+import typer2+3+app = typer.Typer()4+5+6+@app.command("create")7+def cli_create_user(username: str):8+ typer.echo(f"Creating user: {username}")9+10+11+@app.command("delete")12+def cli_delete_user(username: str):13+ typer.echo(f"Deleting user: {username}")14+15+16+if __name__ == "__main__":17+ app()added:docs/tutorial/commands.md+555 added
1+We have seen how to create a CLI program with possibly several *CLI Options* and *CLI Arguments*.2+3+But **Typer** allows you to create CLI programs with several commands (also known as subcommands).4+5+For example, the program `git` has several commands.6+7+One command of `git` is `git push`. And `git push` in turn takes its own *CLI arguments* and *CLI options*.8+9+For example:10+11+<div class="termy">12+13+```console14+// The push command with no parameters15+$ git push16+17+---> 100%18+19+// The push command with one CLI option --set-upstream and 2 CLI arguments20+$ git push --set-upstream origin master21+22+---> 100%23+```24+25+</div>26+27+Another command of `git` is `git pull`, it also has some *CLI parameters*.28+29+It's like if the same big program `git` had several small programs inside.30+31+!!! tip32+ A command looks the same as a *CLI argument*, it's just some name without a preceding `--`. But commands have predefined name, and are used to group different sets of functionalities into the same CLI application.33+34+## Command or subcommand35+36+It's common to call a CLI program a "command".37+38+But when one of these programs have subcommands, those subcommands are also frequently called just "commands".39+40+Have that in mind so you don't get confused.41+42+Here I'll use **CLI application** or **program** to refer to the program you are building in Python with Typer, and **command** to refer to one of these "subcommands" of your program.43+44+## Explicit application45+46+Before creating CLI applications with multiple commands/subcommands we need to understand how to create an explicit `typer.Typer()` application.47+48+In the *CLI Options* and *CLI Argument* tutorials you have seen how to create a single function and then pass that function to `typer.run()`.49+50+For example:51+52+```Python hl_lines="9"53+{!./src/first_steps/tutorial002.py!}54+```55+56+But that is actually a shortcut. Under the hood, **Typer** converts that to a CLI application with `typer.Typer()` and executes it. All that inside of `typer.run()`.57+58+There's also a more explicit way to achieve the same:59+60+```Python hl_lines="3 6 12"61+{!./src/commands/tutorial001.py!}62+```63+64+When you use `typer.run()`, **Typer** is doing more or less the same as above, it will:65+66+* Create a new `typer.Typer()` "application".67+* Create a new "`command`" with your function.68+* Call the same "application" as if it was a function with "`app()`".69+70+!!! info "`@decorator` Info"71+ That `@something` syntax in Python is called a "decorator".72+73+ You put it on top of a function. Like a pretty decorative hat (I guess that's where the term came from).74+75+ A "decorator" takes the function below and does something with it.76+77+ In our case, this decorator tells **Typer** that the function below is a "`command`".78+79+Both ways, with `typer.run()` and creating the explicit application, achieve the same.80+81+!!! tip82+ If your use case is solved with just `typer.run()`, that's fine, you don't have to create the explicit `app` and use `@app.command()`, etc.83+84+ You might want to do that later when your app needs the extra features, but if it doesn't need them yet, that's fine.85+86+If you run the second example, with the explicit `app`, it works exactly the same:87+88+<div class="termy">89+90+```console91+// Without a CLI argument92+$ python main.py93+94+Usage: main.py [OPTIONS] NAME95+Try "main.py --help" for help.96+97+Error: Missing argument "NAME".98+99+// With the NAME CLI argument100+$ python main.py Camila101+102+Hello Camila103+104+// Asking for help105+$ python main.py --help106+107+Usage: main.py [OPTIONS] NAME108+109+Options:110+ --install-completion Install completion for the current shell.111+ --show-completion Show completion for the current shell, to copy it or customize the installation.112+ --help Show this message and exit.113+```114+115+</div>116+117+## A CLI application with multiple commands118+119+Coming back to the CLI applications with multiple commands/subcommands, **Typer** allows creating CLI applications with multiple of them.120+121+Now that you know how to create an explicit `typer.Typer()` application and add one command, let's see how to add multiple commands.122+123+Let's say that we have a CLI application to manage users.124+125+We'll have a command to `create` users and another command to `delete` them.126+127+To begin, let's say it can only create and delete one single predefined user:128+129+```Python hl_lines="6 11"130+{!./src/commands/tutorial002.py!}131+```132+133+Now we have a CLI application with 2 commands, `create` and `delete`:134+135+<div class="termy">136+137+```console138+// Check the help139+$ python main.py --help140+141+Usage: main.py [OPTIONS] COMMAND [ARGS]...142+143+Options:144+ --install-completion Install completion for the current shell.145+ --show-completion Show completion for the current shell, to copy it or customize the installation.146+ --help Show this message and exit.147+148+Commands:149+ create150+ delete151+152+// Test them153+$ python main.py create154+155+Creating user: Hiro Hamada156+157+$ python main.py delete158+159+Deleting user: Hiro Hamada160+161+// Now we have 2 commands! 🎉162+```163+164+</div>165+166+Notice that the help text now shows the 2 commands: `create` and `delete`.167+168+!!! tip169+ By default, the names of the commands are generated from the function name.170+171+## Command *CLI arguments*172+173+The same way as with a CLI application with a single command, subcommands (or just "commands") can also have their own *CLI arguments*:174+175+```Python hl_lines="7 12"176+{!./src/commands/tutorial003.py!}177+```178+179+<div class="termy">180+181+```console182+// Check the help for create183+$ python main.py create --help184+185+Usage: main.py create [OPTIONS] USERNAME186+187+Options:188+ --help Show this message and exit.189+190+// Call it with a CLI argument191+$ python main.py create Camila192+193+Creating user: Camila194+195+// The same for delete196+$ python main.py delete Camila197+198+Deleting user: Camila199+```200+201+</div>202+203+!!! tip204+ Everything to the *right* of the *command* are *CLI parameters* (*CLI arguments* and *CLI options*) for that command.205+206+!!! note "Technical Details"207+ Actually, it's everything to the right of that command, *before any subcommand*.208+209+ It's possible to have groups of *subcommands*, it's like if one *command* also had *subcommands*. And then those *subcommands* could have their own *CLI parameters*, taking their own *CLI parameters*.210+211+ You will see about them later in another section.212+213+## Command *CLI options*214+215+Commands can also have their own *CLI options*.216+217+In fact, each command can have different *CLI arguments* and *CLI options*:218+219+```Python hl_lines="7 13 14 24 33"220+{!./src/commands/tutorial004.py!}221+```222+223+Here we have multiple commands, with different *CLI parameters*:224+225+* `create`:226+ * `username`: a *CLI argument*.227+* `delete`:228+ * `username`: a *CLI argument*.229+ * `--force`: a *CLI option*, if not provided, it's prompted.230+* `delete-all`:231+ * `--force`: a *CLI option*, if not provided, it's prompted.232+* `init`:233+ * Doesn't take any *CLI parameters*.234+235+<div class="termy">236+237+```console238+// Check the help239+python main.py --help240+241+Usage: main.py [OPTIONS] COMMAND [ARGS]...242+243+Options:244+ --install-completion Install completion for the current shell.245+ --show-completion Show completion for the current shell, to copy it or customize the installation.246+ --help Show this message and exit.247+248+Commands:249+ create250+ delete251+ delete-all252+ info253+```254+255+</div>256+257+!!! tip258+ Check the command `delete-all`, by default command names are generated from the function name, replacing `_` with `-`.259+260+Test it:261+262+<div class="termy">263+264+```console265+// Check the command create266+$ python main.py create Camila267+268+Creating user: Camila269+270+// Now test the command delete271+$ python main.py delete Camila272+273+# Are you sure you want to delete the user? [y/N]: $ y274+275+Deleting user: Camila276+277+$ python main.py delete Wade278+279+# Are you sure you want to delete the user? [y/N]: $ n280+281+Operation cancelled282+283+// And finally, the command delete-all284+// Notice it doesn't have CLI arguments, only a CLI option285+286+$ python main.py delete-all287+288+# Are you sure you want to delete ALL users? [y/N]: $ y289+290+Deleting all users291+292+$ python main.py delete-all293+294+# Are you sure you want to delete ALL users? [y/N]: $ n295+296+Operation cancelled297+298+// And if you pass the --force CLI option, it doesn't need to confirm299+300+$ python main.py delete-all --force301+302+Deleting all users303+304+// And init that doesn't take any CLI parameter305+$ python main.py init306+307+Initializing user database308+```309+310+</div>311+312+## Command help313+314+The same as before, you can add help for the commands in the docstrings and the *CLI options*.315+316+And the `typer.Typer()` application receives a parameter `help` that you can pass with the main help text for your CLI program:317+318+```Python hl_lines="3 8 9 10 20 23 24 25 26 27 39 42 43 44 45 46 55 56 57"319+{!./src/commands/tutorial005.py!}320+```321+322+Check it:323+324+<div class="termy">325+326+```console327+// Check the new help328+$ python main.py --help329+330+Usage: main.py [OPTIONS] COMMAND [ARGS]...331+332+ Awesome CLI user manager.333+334+Options:335+ --install-completion Install completion for the current shell.336+ --show-completion Show completion for the current shell, to copy it or customize the installation.337+ --help Show this message and exit.338+339+Commands:340+ create Create a new user with USERNAME.341+ delete Delete a user with USERNAME.342+ delete-all Delete ALL users in the database.343+ init Initialize the users database.344+345+// Now the commands have inline help 🎉346+347+// Check the help for create348+$ python main.py create --help349+350+Usage: main.py create [OPTIONS] USERNAME351+352+ Create a new user with USERNAME.353+354+Options:355+ --help Show this message and exit.356+357+// Check the help for delete358+$ python main.py delete --help359+360+Usage: main.py delete [OPTIONS] USERNAME361+362+ Delete a user with USERNAME.363+364+ If --force is not used, will ask for confirmation.365+366+Options:367+ --force / --no-force Force deletion without confirmation. [required]368+ --help Show this message and exit.369+370+// Check the help for delete-all371+$ python main.py delete-all --help372+373+Usage: main.py delete-all [OPTIONS]374+375+ Delete ALL users in the database.376+377+ If --force is not used, will ask for confirmation.378+379+Options:380+ --force / --no-force Force deletion without confirmation. [required]381+ --help Show this message and exit.382+383+// Check the help for init384+$ python main.py init --help385+386+Usage: main.py init [OPTIONS]387+388+ Initialize the users database.389+390+Options:391+ --help Show this message and exit.392+```393+394+</div>395+396+!!! tip397+ `typer.Typer()` receives several other parameters for other things, we'll see that later.398+399+ You will also see how to use "Callbacks" later, and those include a way to add this same help message in a function docstring.400+401+## Custom command name402+403+By default, the command names are generated from the function name.404+405+So, if your function is something like:406+407+```Python408+def create(username: str):409+ ...410+```411+412+Then the command name will be `create`.413+414+But if you already had a function called `create()` somewhere in your code, you would have to name your CLI function differently.415+416+And what if you wanted the command to still be named `create`?417+418+For this, you can set the name of the command in the first parameter for the `@app.command()` decorator:419+420+```Python hl_lines="6 11"421+{!./src/commands/tutorial006.py!}422+```423+424+Now, even though the functions are named `cli_create_user()` and `cli_delete_user()`, the commands will still be named `create` and `delete`:425+426+<div class="termy">427+428+```console429+$ python main.py --help430+431+Usage: main.py [OPTIONS] COMMAND [ARGS]...432+433+Options:434+ --install-completion Install completion for the current shell.435+ --show-completion Show completion for the current shell, to copy it or customize the installation.436+ --help Show this message and exit.437+438+Commands:439+ create440+ delete441+442+// Test it443+$ python main.py create Camila444+445+Creating user: Camila446+```447+448+</div>449+450+## One command vs multiple commands451+452+You might have noticed that if you create a single command, as in the first example:453+454+```Python hl_lines="3 6 12"455+{!./src/commands/tutorial001.py!}456+```457+458+**Typer** is smart enough to create a CLI application with that single function as the main CLI application, not as a command/subcommand:459+460+<div class="termy">461+462+```console463+// Without a CLI argument464+$ python main.py465+466+Usage: main.py [OPTIONS] NAME467+Try "main.py --help" for help.468+469+Error: Missing argument "NAME".470+471+// With the NAME CLI argument472+$ python main.py Camila473+474+Hello Camila475+476+// Asking for help477+$ python main.py478+479+Usage: main.py [OPTIONS] NAME480+481+Options:482+ --install-completion Install completion for the current shell.483+ --show-completion Show completion for the current shell, to copy it or customize the installation.484+ --help Show this message and exit.485+```486+487+</div>488+489+!!! tip490+ Notice that it doesn't show a command `main`, even though the function name is `main`.491+492+But if you add multiple commands, **Typer** will create one *CLI command* for each one of them:493+494+```Python hl_lines="6 11"495+{!./src/commands/tutorial002.py!}496+```497+498+Here we have 2 commands `create` and `delete`:499+500+<div class="termy">501+502+```console503+// Check the help504+$ python main.py --help505+506+Usage: main.py [OPTIONS] COMMAND [ARGS]...507+508+Options:509+ --install-completion Install completion for the current shell.510+ --show-completion Show completion for the current shell, to copy it or customize the installation.511+ --help Show this message and exit.512+513+Commands:514+ create515+ delete516+517+// Test the commands518+$ python main.py create519+520+Creating user: Hiro Hamada521+522+$ python main.py delete523+524+Deleting user: Hiro Hamada525+```526+527+</div>528+529+!!! tip530+ This is **Typer**'s behavior by default, but you could still create a CLI application with one single command, like:531+532+ ```533+ $ python main.py main534+ ```535+536+ instead of just:537+538+ ```539+ $ python main.py540+ ```541+542+ You will learn more about this in the section about application Callbacks.543+544+## Decorator Technical Details545+546+When you use `@app.command()` the function under the decorator is registered in the **Typer** application and is then used later by the application.547+548+But Typer doesn't modify that function itself, the function is left as is.549+550+That means that if your function is simple enough that you could create it without using `typer.Option()` or `typer.Argument()`, you could use the same function for a **Typer** application and a **FastAPI** application putting both decorators on top, or similar tricks.551+552+!!! note "Click Technical Details"553+ This behavior is a design difference with Click.554+555+ In Click, when you add a `@click.command()` decorator it actually modifies the function underneath and replaces it with an object.modified:mkdocs.yml+1 added
23 unmodified lines24252627282930313234 unmodified lines23 unmodified lines - Tutorial - User Guide - Intro: 'tutorial/index.md' - First Steps: 'tutorial/first-steps.md' - CLI Options: 'tutorial/options.md' - CLI Arguments: 'tutorial/arguments.md' - Commands: 'tutorial/commands.md' - Alternatives, Inspiration and Comparisons: 'alternatives.md' - Help Typer - Get Help: 'help-typer.md' - Development - Contributing: 'contributing.md' - Release Notes: release-notes.md34 unmodified lines