:memo: :sparkles: Add colors module and docs for printing and terminating, including tests.
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 GitHub · parents 2af53e6, bb0bbfa · Browse files · 15 files·+402 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
15 files+402 added−0 removed
- tests:+102 added−0 removed
- other:+300 added−0 removed
Provenance
- Commit
0513070- Tree
48adaf5- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
2af53e6- Parent 2
bb0bbfa
15 files changed+402 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>added:tests/test_tutorial/test_terminating/__init__.py
added:tests/test_tutorial/test_terminating/test_tutorial001.py+35 added
1+import subprocess2+3+import typer4+from typer.testing import CliRunner5+6+from terminating import tutorial001 as mod7+8+runner = CliRunner()9+10+app = typer.Typer()11+app.command()(mod.main)12+13+14+def test_cli():15+ result = runner.invoke(app, ["Camila"])16+ assert result.exit_code == 017+ assert "User created: Camila" in result.output18+ assert "Notification sent for new user: Camila" in result.output19+20+21+def test_existing():22+ result = runner.invoke(app, ["rick"])23+ assert result.exit_code == 024+ assert "The user already exists" in result.output25+ assert "Notification sent for new user" not in result.output26+27+28+def test_script():29+ result = subprocess.run(30+ ["coverage", "run", mod.__file__, "--help"],31+ stdout=subprocess.PIPE,32+ stderr=subprocess.PIPE,33+ encoding="utf-8",34+ )35+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_terminating/test_tutorial002.py+33 added
1+import subprocess2+3+import typer4+from typer.testing import CliRunner5+6+from terminating import tutorial002 as mod7+8+runner = CliRunner()9+10+app = typer.Typer()11+app.command()(mod.main)12+13+14+def test_cli():15+ result = runner.invoke(app, ["Camila"])16+ assert result.exit_code == 017+ assert "New user created: Camila" in result.output18+19+20+def test_root():21+ result = runner.invoke(app, ["root"])22+ assert result.exit_code == 123+ assert "The root user is reserved" in result.output24+25+26+def test_script():27+ result = subprocess.run(28+ ["coverage", "run", mod.__file__, "--help"],29+ stdout=subprocess.PIPE,30+ stderr=subprocess.PIPE,31+ encoding="utf-8",32+ )33+ assert "Usage" in result.stdoutadded:tests/test_tutorial/test_terminating/test_tutorial003.py+34 added
1+import subprocess2+3+import typer4+from typer.testing import CliRunner5+6+from terminating import tutorial003 as mod7+8+runner = CliRunner()9+10+app = typer.Typer()11+app.command()(mod.main)12+13+14+def test_cli():15+ result = runner.invoke(app, ["Camila"])16+ assert result.exit_code == 017+ assert "New user created: Camila" in result.output18+19+20+def test_root():21+ result = runner.invoke(app, ["root"])22+ assert result.exit_code == 123+ assert "The root user is reserved" in result.output24+ assert "Aborted!" in result.output25+26+27+def test_script():28+ result = subprocess.run(29+ ["coverage", "run", mod.__file__, "--help"],30+ stdout=subprocess.PIPE,31+ stderr=subprocess.PIPE,32+ encoding="utf-8",33+ )34+ assert "Usage" in result.stdoutmodified:typer/__init__.py+1 added
25 unmodified lines26 get_text_stream,27 open_file,28 )29 30+from . import colors # noqa31 from .main import Typer, run # noqa32 from .models import ( # noqa33 Context,34 FileBinaryRead,5 unmodified linesadded:typer/colors.py+20 added
1+# Variable names to colors, just for completion2+BLACK = "black"3+RED = "red"4+GREEN = "green"5+YELLOW = "yellow"6+BLUE = "blue"7+MAGENTA = "magenta"8+CYAN = "cyan"9+WHITE = "white"10+11+RESET = "reset"12+13+BRIGHT_BLACK = "bright_black"14+BRIGHT_RED = "bright_red"15+BRIGHT_GREEN = "bright_green"16+BRIGHT_YELLOW = "bright_yellow"17+BRIGHT_BLUE = "bright_blue"18+BRIGHT_MAGENTA = "bright_magenta"19+BRIGHT_CYAN = "bright_cyan"20+BRIGHT_WHITE = "bright_white"modified:mkdocs.yml+2 added
21 unmodified lines22 - Features: 'features.md'23 - Tutorial - User Guide:24 - Tutorial - User Guide - Intro: 'tutorial/index.md'25 - First Steps: 'tutorial/first-steps.md'26+ - Printing and Colors: 'tutorial/printing.md'27+ - Terminating: 'tutorial/terminating.md'28 - CLI Arguments: 'tutorial/arguments.md'29 - CLI Options:30 - CLI Options Intro: 'tutorial/options/index.md'31 - CLI Options with Help: 'tutorial/options/help.md'56 unmodified lines