:memo: Add CLI Options docs and examples
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 13e0c8e · Browse files · 8 files·+333 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+333 added−0 removed
- other:+333 added−0 removed
Provenance
- Commit
3454463- Tree
8efb37d- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
Sebastián Ramírez <tiangolo@gmail.com>- Parent
13e0c8e
8 files changed+333 added−0 removed
added:docs/src/options/tutorial001.py+21 added
1+import typer2+3+4+def main(5+ name: str,6+ lastname: str = typer.Option("", help="Last name of person to greet."),7+ formal: bool = typer.Option(False, help="Say hi formally."),8+):9+ """10+ Say hi to NAME, optionally with a --lastname.11+12+ If --formal is used, say hi very formally.13+ """14+ if formal:15+ typer.echo(f"Good day Ms. {name} {lastname}.")16+ else:17+ typer.echo(f"Hello {name} {lastname}")18+19+20+if __name__ == "__main__":21+ typer.run(main)added:docs/src/options/tutorial002.py+9 added
1+import typer2+3+4+def main(name: str, lastname: str = typer.Option(...)):5+ typer.echo(f"Hello {name} {lastname}")6+7+8+if __name__ == "__main__":9+ typer.run(main)added:docs/src/options/tutorial003.py+9 added
1+import typer2+3+4+def main(name: str, lastname: str = typer.Option(..., prompt=True)):5+ typer.echo(f"Hello {name} {lastname}")6+7+8+if __name__ == "__main__":9+ typer.run(main)added:docs/src/options/tutorial004.py+12 added
1+import typer2+3+4+def main(5+ name: str,6+ lastname: str = typer.Option(..., prompt="Please tell me your last name"),7+):8+ typer.echo(f"Hello {name} {lastname}")9+10+11+if __name__ == "__main__":12+ typer.run(main)added:docs/src/options/tutorial005.py+9 added
1+import typer2+3+4+def main(project_name: str = typer.Option(..., prompt=True, confirmation_prompt=True)):5+ typer.echo(f"Deleting project {project_name}")6+7+8+if __name__ == "__main__":9+ typer.run(main)added:docs/src/options/tutorial006.py+9 added
1+import typer2+3+4+def main(fullname: str = typer.Option("Wade Wilson", show_default=True)):5+ typer.echo(f"Hello {fullname}")6+7+8+if __name__ == "__main__":9+ typer.run(main)added:docs/tutorial/options.md+263 added
1+## *CLI options* with help2+3+In the *First Steps* section you saw how to add help for a CLI app/command by adding it to a function's <abbr title="a multi-line string as the first expression inside a function (not assigned to any variable) used for documentation">docstring</abbr>.4+5+Here's how that last example looked like:6+7+```Python8+{!./src/first_steps/tutorial006.py!}9+```10+11+Now we'll add a *help* section to the *CLI options*:12+13+```Python hl_lines="6 7"14+{!./src/options/tutorial001.py!}15+```16+17+We are replacing the default values we had before with `typer.Option()`.18+19+As we no longer have a default value there, the first parameter to `typer.Option()` serves the same purpose of defining that default value.20+21+So, if we had:22+23+```Python24+lastname: str = ""25+```26+27+now we write:28+29+```Python30+lastname: str = typer.Option("")31+```32+33+And both forms achieve the same: a *CLI option* with a default value of an empty string (`""`).34+35+And then we can pass the `help` keyword parameter:36+37+```Python38+lastname: str = typer.Option("", help="this option does this and that")39+```40+41+to create the help for that *CLI option*.42+43+Copy that example from above to a file `main.py`.44+45+Test it:46+47+<div class="termy">48+49+```console50+$ python main.py --help51+52+Usage: main.py [OPTIONS] NAME53+54+ Say hi to NAME, optionally with a --lastname.55+56+ If --formal is used, say hi very formally.57+58+Options:59+ --lastname TEXT Last name of person to greet.60+ --formal / --no-formal Say hi formally.61+ --install-completion Install completion for the current shell.62+ --show-completion Show completion for the current shell, to copy it or customize the installation.63+ --help Show this message and exit.64+65+// Now you have a help text for the --lastname and --formal CLI options 🎉66+```67+68+</div>69+70+## Make a *CLI option* required71+72+We said before that *by default*:73+74+* *CLI options* are **optional**75+* *CLI arguments* are **required**76+77+Well, that's how they work *by default*, and that's the convention in many CLI programs and systems.78+79+But if you really want, you can change that.80+81+To make a *CLI option* required, pass `...` to `typer.Option()`.82+83+!!! info84+ If you hadn't seen that `...` before: it is a a special single value, it is <a href="https://docs.python.org/3/library/constants.html#Ellipsis" target="_blank">part of Python and is called "Ellipsis"</a>.85+86+That will tell **Typer** that it's still a *CLI option*, but it doesn't have a default value, and it's required.87+88+Let's make the `--lastname` a required *CLI option*.89+90+We'll also simplify the example to focus on the new parts:91+92+```Python hl_lines="4"93+{!./src/options/tutorial002.py!}94+```95+96+!!! tip97+ You could still add `help` to `typer.Option()` as before, but we are omitting it here to simplify the example.98+99+And test it:100+101+<div class="termy">102+103+```console104+// Pass the NAME CLI argument105+$ python main.py Camila106+107+// We didn't pass the now required --lastname CLI option108+Usage: main.py [OPTIONS] NAME109+Try "main.py --help" for help.110+111+Error: Missing option "--lastname".112+113+// Now update it to pass the required --lastname CLI option114+$ python main.py Camila --lastname Gutiérrez115+116+Hello Camila Gutiérrez117+118+// And if you check the help119+$ python main.py --help120+121+Usage: main.py [OPTIONS] NAME122+123+Options:124+ --lastname TEXT [required]125+ --install-completion Install completion for the current shell.126+ --show-completion Show completion for the current shell, to copy it or customize the installation.127+ --help Show this message and exit.128+129+// It now tells you that --lastname is required 🎉130+```131+132+</div>133+134+## Prompt for a *CLI option*135+136+It's also possible to, instead of just showing an error, ask for the missing value with `prompt=True`:137+138+```Python hl_lines="4"139+{!./src/options/tutorial003.py!}140+```141+142+And then your program will ask the user for it in the terminal:143+144+<div class="termy">145+146+```console147+// Call it with the NAME CLI argument148+$ python main.py Camila149+150+// It asks for the missing CLI option --lastname151+# Lastname: $ Gutiérrez152+153+Hello Camila Gutiérrez154+```155+156+</div>157+158+### Customize the prompt159+160+You can also set a custom prompt, passing the string that you want to use instead of just `True`:161+162+```Python hl_lines="6"163+{!./src/options/tutorial004.py!}164+```165+166+And then your program will ask for it using with your custom prompt:167+168+<div class="termy">169+170+```console171+// Call it with the NAME CLI argument172+$ python main.py Camila173+174+// It uses the custom prompt175+# Please tell me your last name: $ Gutiérrez176+177+Hello Camila Gutiérrez178+```179+180+</div>181+182+## Confirmation prompt183+184+In some cases you could want to prompt for something and then ask the user to confirm it by typing it twice.185+186+You can do it passing the parameter `confirmation_prompt=True`.187+188+Let's say it's a CLI app to delete a project:189+190+```Python hl_lines="4"191+{!./src/options/tutorial005.py!}192+```193+194+And it will prompt the user for a value and then for the confirmation:195+196+<div class="termy">197+198+```console199+$ python main.py200+201+// Your app will first prompt for the project name, and then for the confirmation202+# Project name: $ Old Project203+# Repeat for confirmation: $ Old Project204+205+Deleting project Old Project206+207+// If the user doesn't type the same, receives an error and a new prompt208+$ python main.py209+210+# Project name: $ Old Project211+# Repeat for confirmation: $ New Spice212+213+Error: the two entered values do not match214+215+# Project name: $ Old Project216+# Repeat for confirmation: $ Old Project217+218+Deleting project Old Project219+220+// Now it works 🎉221+```222+223+</div>224+225+## Show default in help226+227+You can tell Typer to show the default value in the help text with `show_default=True`:228+229+```Python hl_lines="4"230+{!./src/options/tutorial006.py!}231+```232+233+And it will show up in the help text:234+235+<div class="termy">236+237+```console238+$ python main.py239+240+Hello Wade Wilson241+242+// Show the help243+$ python main.py --help244+245+Usage: main.py [OPTIONS]246+247+Options:248+ --fullname TEXT [default: Wade Wilson]249+ --install-completion Install completion for the current shell.250+ --show-completion Show completion for the current shell, to copy it or customize the installation.251+ --help Show this message and exit.252+```253+254+</div>255+256+!!! tip257+ Notice the `[default: Wade Wilson]` in the help text.258+259+## Other uses260+261+`typer.Option()` has several other users. For data validation, to enable other features, etc.262+263+But you will see about that later in the docs.modified:mkdocs.yml+1 added
21 unmodified lines22232425262728293034 unmodified lines21 unmodified lines - Features: 'features.md' - Tutorial - User Guide: - Tutorial - User Guide - Intro: 'tutorial/index.md' - First Steps: 'tutorial/first-steps.md' - CLI Options: 'tutorial/options.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