Skip to content
Myr

: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

8 files+333 added−0 removed

added:docs/src/options/tutorial001.py+21 added
1import typer234def 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.1112 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}")181920if __name__ == "__main__":21 typer.run(main)
added:docs/src/options/tutorial002.py+9 added
1import typer234def main(name: str, lastname: str = typer.Option(...)):5 typer.echo(f"Hello {name} {lastname}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/options/tutorial003.py+9 added
1import typer234def main(name: str, lastname: str = typer.Option(..., prompt=True)):5 typer.echo(f"Hello {name} {lastname}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/options/tutorial004.py+12 added
1import typer234def main(5 name: str,6 lastname: str = typer.Option(..., prompt="Please tell me your last name"),7):8 typer.echo(f"Hello {name} {lastname}")91011if __name__ == "__main__":12 typer.run(main)
added:docs/src/options/tutorial005.py+9 added
1import typer234def main(project_name: str = typer.Option(..., prompt=True, confirmation_prompt=True)):5 typer.echo(f"Deleting project {project_name}")678if __name__ == "__main__":9 typer.run(main)
added:docs/src/options/tutorial006.py+9 added
1import typer234def main(fullname: str = typer.Option("Wade Wilson", show_default=True)):5 typer.echo(f"Hello {fullname}")678if __name__ == "__main__":9 typer.run(main)
added:docs/tutorial/options.md+263 added
1## *CLI options* with help23In 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>.45Here's how that last example looked like:67```Python8{!./src/first_steps/tutorial006.py!}9```1011Now we'll add a *help* section to the *CLI options*:1213```Python hl_lines="6 7"14{!./src/options/tutorial001.py!}15```1617We are replacing the default values we had before with `typer.Option()`.1819As we no longer have a default value there, the first parameter to `typer.Option()` serves the same purpose of defining that default value.2021So, if we had:2223```Python24lastname: str = ""25```2627now we write:2829```Python30lastname: str = typer.Option("")31```3233And both forms achieve the same: a *CLI option* with a default value of an empty string (`""`).3435And then we can pass the `help` keyword parameter:3637```Python38lastname: str = typer.Option("", help="this option does this and that")39```4041to create the help for that *CLI option*.4243Copy that example from above to a file `main.py`.4445Test it:4647<div class="termy">4849```console50$ python main.py --help5152Usage: main.py [OPTIONS] NAME5354 Say hi to NAME, optionally with a --lastname.5556 If --formal is used, say hi very formally.5758Options: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.6465// Now you have a help text for the --lastname and --formal CLI options 🎉66```6768</div>6970## Make a *CLI option* required7172We said before that *by default*:7374* *CLI options* are **optional**75* *CLI arguments* are **required**7677Well, that's how they work *by default*, and that's the convention in many CLI programs and systems.7879But if you really want, you can change that.8081To make a *CLI option* required, pass `...` to `typer.Option()`.8283!!! 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>.8586That will tell **Typer** that it's still a *CLI option*, but it doesn't have a default value, and it's required.8788Let's make the `--lastname` a required *CLI option*.8990We'll also simplify the example to focus on the new parts:9192```Python hl_lines="4"93{!./src/options/tutorial002.py!}94```9596!!! tip97 You could still add `help` to `typer.Option()` as before, but we are omitting it here to simplify the example.9899And test it:100101<div class="termy">102103```console104// Pass the NAME CLI argument105$ python main.py Camila106107// We didn't pass the now required --lastname CLI option108Usage: main.py [OPTIONS] NAME109Try "main.py --help" for help.110111Error: Missing option "--lastname".112113// Now update it to pass the required --lastname CLI option114$ python main.py Camila --lastname Gutiérrez115116Hello Camila Gutiérrez117118// And if you check the help119$ python main.py --help120121Usage: main.py [OPTIONS] NAME122123Options: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.128129// It now tells you that --lastname is required 🎉130```131132</div>133134## Prompt for a *CLI option*135136It's also possible to, instead of just showing an error, ask for the missing value with `prompt=True`:137138```Python hl_lines="4"139{!./src/options/tutorial003.py!}140```141142And then your program will ask the user for it in the terminal:143144<div class="termy">145146```console147// Call it with the NAME CLI argument148$ python main.py Camila149150// It asks for the missing CLI option --lastname151# Lastname: $ Gutiérrez152153Hello Camila Gutiérrez154```155156</div>157158### Customize the prompt159160You can also set a custom prompt, passing the string that you want to use instead of just `True`:161162```Python hl_lines="6"163{!./src/options/tutorial004.py!}164```165166And then your program will ask for it using with your custom prompt:167168<div class="termy">169170```console171// Call it with the NAME CLI argument172$ python main.py Camila173174// It uses the custom prompt175# Please tell me your last name: $ Gutiérrez176177Hello Camila Gutiérrez178```179180</div>181182## Confirmation prompt183184In some cases you could want to prompt for something and then ask the user to confirm it by typing it twice.185186You can do it passing the parameter `confirmation_prompt=True`.187188Let's say it's a CLI app to delete a project:189190```Python hl_lines="4"191{!./src/options/tutorial005.py!}192```193194And it will prompt the user for a value and then for the confirmation:195196<div class="termy">197198```console199$ python main.py200201// Your app will first prompt for the project name, and then for the confirmation202# Project name: $ Old Project203# Repeat for confirmation: $ Old Project204205Deleting project Old Project206207// If the user doesn't type the same, receives an error and a new prompt208$ python main.py209210# Project name: $ Old Project211# Repeat for confirmation: $ New Spice212213Error: the two entered values do not match214215# Project name: $ Old Project216# Repeat for confirmation: $ Old Project217218Deleting project Old Project219220// Now it works 🎉221```222223</div>224225## Show default in help226227You can tell Typer to show the default value in the help text with `show_default=True`:228229```Python hl_lines="4"230{!./src/options/tutorial006.py!}231```232233And it will show up in the help text:234235<div class="termy">236237```console238$ python main.py239240Hello Wade Wilson241242// Show the help243$ python main.py --help244245Usage: main.py [OPTIONS]246247Options: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```253254</div>255256!!! tip257 Notice the `[default: Wade Wilson]` in the help text.258259## Other uses260261`typer.Option()` has several other users. For data validation, to enable other features, etc.262263But you will see about that later in the docs.
modified:mkdocs.yml+1 added