:memo: Add docs for printing and terminating
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 0ed9efe · Browse files · 9 files·+279 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
9 files+279 added−0 removed
- other:+279 added−0 removed
Provenance
- Commit
aadca21- Tree
45799ee- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
Sebastián Ramírez <tiangolo@gmail.com>- Parent
0ed9efe
9 files changed+279 added−0 removed
added:docs/src/printing/tutorial001.py+15 added
1+import typer2+3+4+def main(good: bool = True):5+ message_start = "everything is "6+ if good:7+ ending = typer.style("good", fg=typer.colors.GREEN, bold=True)8+ else:9+ ending = typer.style("bad", fg=typer.colors.WHITE, bg=typer.colors.RED)10+ message = message_start + ending11+ typer.echo(message)12+13+14+if __name__ == "__main__":15+ typer.run(main)added:docs/src/printing/tutorial002.py+9 added
1+import typer2+3+4+def main(name: str):5+ typer.secho(f"Welcome here {name}", fg=typer.colors.MAGENTA)6+7+8+if __name__ == "__main__":9+ typer.run(main)added:docs/src/terminating/tutorial001.py+25 added
1+import typer2+3+existing_usernames = ["rick", "morty"]4+5+6+def maybe_create_user(username: str):7+ if username in existing_usernames:8+ typer.echo("The user already exists")9+ raise typer.Exit()10+ else:11+ typer.echo(f"User created: {username}")12+13+14+def send_new_user_notification(username: str):15+ # Somehow send a notification here for the new user, maybe an email16+ typer.echo(f"Notification sent for new user: {username}")17+18+19+def main(username: str):20+ maybe_create_user(username=username)21+ send_new_user_notification(username=username)22+23+24+if __name__ == "__main__":25+ typer.run(main)added:docs/src/terminating/tutorial002.py+12 added
1+import typer2+3+4+def main(username: str):5+ if username == "root":6+ typer.echo("The root user is reserved")7+ raise typer.Exit(code=1)8+ typer.echo(f"New user created: {username}")9+10+11+if __name__ == "__main__":12+ typer.run(main)added:docs/src/terminating/tutorial003.py+12 added
1+import typer2+3+4+def main(username: str):5+ if username == "root":6+ typer.echo("The root user is reserved")7+ raise typer.Abort()8+ typer.echo(f"New user created: {username}")9+10+11+if __name__ == "__main__":12+ typer.run(main)modified:docs/tutorial/first-steps.md+3 added
4 unmodified lines5 ```Python6 {!./src/first_steps/tutorial001.py!}7 ```8 9+!!! tip10+ You will learn more about `typer.echo()` later in the docs.11+12 Copy that to a file `main.py`.13 14 Test it:15 413 unmodified linesadded:docs/tutorial/printing.md+83 added
1+You can use `typer.echo()` to print to the screen:2+3+```Python hl_lines="5"4+{!./src/first_steps/tutorial001.py!}5+```6+7+The reason to use `typer.echo()` instead of just `print()` is that it applies some error corrections in case the terminal is misconfigured, and it will properly output color if it's supported.8+9+!!! info10+ `typer.echo()` comes directly from Click, you can read more about it in <a href="https://click.palletsprojects.com/en/7.x/quickstart/#echoing" target="_blank">Click's docs</a>.11+12+Check it:13+14+<div class="termy">15+16+```console17+$ python main.py18+19+Hello World20+```21+22+</div>23+24+## Color25+26+!!! info27+ For colors to work correctly on Windows you need to also install <a href="https://pypi.org/project/colorama/" target="_blank">`colorama`</a>.28+29+ You don't need to call `colorama.init()`. Typer (actually Click) will handle it underneath.30+31+!!! note "Technical Details"32+ The way color works in terminals is by using some codes (ASCII codes) as part of the text.33+34+ So, a colored text is still just a `str`.35+36+You can create colored strings to output to the terminal with `typer.style()`, that gives you `str`s that you can then pass to `typer.echo()`:37+38+```Python hl_lines="7 9"39+{!./src/printing/tutorial001.py!}40+```41+42+!!! tip43+ The parameters `fg` and `bg` receive strings with the color names. You could simply pass `fg="green"` and `bg="red"`.44+45+ But **Typer** provides them all as variables like `typer.colors.GREEN` just so you can use autocompletion while selecting them.46+47+Check it:48+49+<div class="use-termynal" data-termynal>50+<span data-ty="input">python main.py</span>51+<span data-ty>everything is <span style="color: green; font-weight: bold;">good</span></span>52+<span data-ty="input">python main.py --no-good</span>53+<span data-ty>everything is <span style="color: white; background-color: red;">bad</span></span>54+</div>55+56+You can pass these function arguments to `typer.style()`:57+58+* `fg`: the foreground color.59+* `bg`: the background color.60+* `bold`: enable or disable bold mode.61+* `dim`: enable or disable dim mode. This is badly supported.62+* `underline`: enable or disable underline.63+* `blink`: enable or disable blinking.64+* `reverse`: enable or disable inverse rendering (foreground becomes background and the other way round).65+* `reset`: by default a reset-all code is added at the end of the string which means that styles do not carry over. This can be disabled to compose styles.66+67+!!! info68+ You can read more about it in <a href="https://click.palletsprojects.com/en/7.x/api/#click.style" target="_blank">Click's docs about `style()`</a>69+70+## `typer.secho()` - style and print71+72+There's a shorter form to style and print at the same time with `typer.secho()` it's like `typer.echo()` but also adds style like `typer.style()`:73+74+```Python hl_lines="5"75+{!./src/printing/tutorial002.py!}76+```77+78+Check it:79+80+<div class="use-termynal" data-termynal>81+<span data-ty="input">python main.py Camila</span>82+<span style="color: magenta;" data-ty>Welcome here Camila</span>83+</div>added:docs/tutorial/terminating.md+118 added
1+There are some cases where you might want to terminate a command at some point, and stop all subsequent execution.2+3+It could be that your code determined that the program completed successfully, or it could be an operation aborted.4+5+## `Exit` a CLI program6+7+You can normally just let the code of your CLI program finish its execution, but in some scenarios, you might want to terminate at some point in the middle of it. And prevent any subsequent code to run.8+9+This doesn't have to mean that there's an error, just that nothing else needs to be executed.10+11+In that case, you can raise a `typer.Exit()` exception:12+13+```Python hl_lines="9"14+{!./src/terminating/tutorial001.py!}15+```16+17+There are several things to see in this example.18+19+* The CLI program is the function `main()`, not the others. This is the one that takes a *CLI argument*.20+* The function `maybe_create_user()` can terminate the program by raising `typer.Exit()`.21+* If the program is terminated by `maybe_create_user()` then `send_new_user_notification()` will never execute inside of `main()`.22+23+Check it:24+25+<div class="termy">26+27+```console28+$ python main.py Camila29+30+User created: Camila31+Notification sent for new user: Camila32+33+// Try with an existing user34+$ python main.py rick35+36+The user already exists37+38+// Notice that the notification code was never run, the second message is not printed39+```40+41+</div>42+43+!!! tip44+ Even though you are rasing an exception, it doesn't necessarily mean there's an error.45+46+ This is done with an exception because it works as an "error" and stops all execution.47+ 48+ But then **Typer** (actually Click) catches it and just terminates the program normally.49+50+## Exit with an error51+52+`typer.Exit()` takes an optional `code` parameter. By default, `code` is `0`, meaning there was no error.53+54+You can pass a `code` with a number other than `0` to tell the terminal that there was an error in the execution of the program:55+56+```Python hl_lines="7"57+{!./src/terminating/tutorial002.py!}58+```59+60+Check it:61+62+<div class="termy">63+64+```console65+$ python main.py Camila66+67+New user created: Camila68+69+// Print the result code of the last program executed70+$ echo $?71+72+073+74+// Now make it exit with an error75+$ python main.py root76+77+The root user is reserved78+79+// Print the result code of the last program executed80+$ echo $?81+82+183+84+// 1 means there was an error, 0 means no errors.85+```86+87+</div>88+89+!!! tip90+ The error code might be used by other programs (for example a Bash script) that execute with your CLI program.91+92+## Abort93+94+There's a special exception that you can use to "abort" a program.95+96+It works more or less the same as `typer.Exit()` but will print `"Aborted!"` to the screen and can be useful in certain cases later to make it explicit that the execution was aborted:97+98+```Python hl_lines="7"99+{!./src/terminating/tutorial003.py!}100+```101+102+Check it:103+104+<div class="termy">105+106+```console107+$ python main.py Camila108+109+New user created: Camila110+111+// Now make it exit with an error112+$ python main.py root113+114+The root user is reserved115+Aborted!116+```117+118+</div>modified:mkdocs.yml+2 added
21 unmodified lines2223242526272829303156 unmodified lines21 unmodified lines - Features: 'features.md' - Tutorial - User Guide: - Tutorial - User Guide - Intro: 'tutorial/index.md' - First Steps: 'tutorial/first-steps.md' - Printing and Colors: 'tutorial/printing.md' - Terminating: 'tutorial/terminating.md' - CLI Arguments: 'tutorial/arguments.md' - CLI Options: - CLI Options Intro: 'tutorial/options/index.md' - CLI Options with Help: 'tutorial/options/help.md'56 unmodified lines