Skip to content
Myr

: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

15 files+402 added−0 removed

added:docs/src/printing/tutorial001.py+15 added
1import typer234def 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)121314if __name__ == "__main__":15 typer.run(main)
added:docs/src/printing/tutorial002.py+9 added
1import typer234def main(name: str):5 typer.secho(f"Welcome here {name}", fg=typer.colors.MAGENTA)678if __name__ == "__main__":9 typer.run(main)
added:docs/src/terminating/tutorial001.py+25 added
1import typer23existing_usernames = ["rick", "morty"]456def 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}")121314def 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}")171819def main(username: str):20 maybe_create_user(username=username)21 send_new_user_notification(username=username)222324if __name__ == "__main__":25 typer.run(main)
added:docs/src/terminating/tutorial002.py+12 added
1import typer234def 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}")91011if __name__ == "__main__":12 typer.run(main)
added:docs/src/terminating/tutorial003.py+12 added
1import typer234def 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}")91011if __name__ == "__main__":12 typer.run(main)
modified:docs/tutorial/first-steps.md+3 added
4 unmodified lines
5```Python6{!./src/first_steps/tutorial001.py!}7```89!!! tip10 You will learn more about `typer.echo()` later in the docs.1112Copy that to a file `main.py`.1314Test it:15
413 unmodified lines
added:docs/tutorial/printing.md+83 added
1You can use `typer.echo()` to print to the screen:23```Python hl_lines="5"4{!./src/first_steps/tutorial001.py!}5```67The 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.89!!! 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>.1112Check it:1314<div class="termy">1516```console17$ python main.py1819Hello World20```2122</div>2324## Color2526!!! info27 For colors to work correctly on Windows you need to also install <a href="https://pypi.org/project/colorama/" target="_blank">`colorama`</a>.2829 You don't need to call `colorama.init()`. Typer (actually Click) will handle it underneath.3031!!! note "Technical Details"32 The way color works in terminals is by using some codes (ASCII codes) as part of the text.3334 So, a colored text is still just a `str`.3536You 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()`:3738```Python hl_lines="7 9"39{!./src/printing/tutorial001.py!}40```4142!!! tip43 The parameters `fg` and `bg` receive strings with the color names. You could simply pass `fg="green"` and `bg="red"`.4445 But **Typer** provides them all as variables like `typer.colors.GREEN` just so you can use autocompletion while selecting them.4647Check it:4849<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>5556You can pass these function arguments to `typer.style()`:5758* `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.6667!!! 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>6970## `typer.secho()` - style and print7172There'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()`:7374```Python hl_lines="5"75{!./src/printing/tutorial002.py!}76```7778Check it:7980<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
1There are some cases where you might want to terminate a command at some point, and stop all subsequent execution.23It could be that your code determined that the program completed successfully, or it could be an operation aborted.45## `Exit` a CLI program67You 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.89This doesn't have to mean that there's an error, just that nothing else needs to be executed.1011In that case, you can raise a `typer.Exit()` exception:1213```Python hl_lines="9"14{!./src/terminating/tutorial001.py!}15```1617There are several things to see in this example.1819* 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()`.2223Check it:2425<div class="termy">2627```console28$ python main.py Camila2930User created: Camila31Notification sent for new user: Camila3233// Try with an existing user34$ python main.py rick3536The user already exists3738// Notice that the notification code was never run, the second message is not printed39```4041</div>4243!!! tip44 Even though you are rasing an exception, it doesn't necessarily mean there's an error.4546 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.4950## Exit with an error5152`typer.Exit()` takes an optional `code` parameter. By default, `code` is `0`, meaning there was no error.5354You 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:5556```Python hl_lines="7"57{!./src/terminating/tutorial002.py!}58```5960Check it:6162<div class="termy">6364```console65$ python main.py Camila6667New user created: Camila6869// Print the result code of the last program executed70$ echo $?717207374// Now make it exit with an error75$ python main.py root7677The root user is reserved7879// Print the result code of the last program executed80$ echo $?818218384// 1 means there was an error, 0 means no errors.85```8687</div>8889!!! tip90 The error code might be used by other programs (for example a Bash script) that execute with your CLI program.9192## Abort9394There's a special exception that you can use to "abort" a program.9596It 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:9798```Python hl_lines="7"99{!./src/terminating/tutorial003.py!}100```101102Check it:103104<div class="termy">105106```console107$ python main.py Camila108109New user created: Camila110111// Now make it exit with an error112$ python main.py root113114The root user is reserved115Aborted!116```117118</div>
added:tests/test_tutorial/test_terminating/__init__.py
added:tests/test_tutorial/test_terminating/test_tutorial001.py+35 added
1import subprocess23import typer4from typer.testing import CliRunner56from terminating import tutorial001 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def 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.output192021def 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.output262728def 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.stdout
added:tests/test_tutorial/test_terminating/test_tutorial002.py+33 added
1import subprocess23import typer4from typer.testing import CliRunner56from terminating import tutorial002 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_cli():15 result = runner.invoke(app, ["Camila"])16 assert result.exit_code == 017 assert "New user created: Camila" in result.output181920def test_root():21 result = runner.invoke(app, ["root"])22 assert result.exit_code == 123 assert "The root user is reserved" in result.output242526def 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.stdout
added:tests/test_tutorial/test_terminating/test_tutorial003.py+34 added
1import subprocess23import typer4from typer.testing import CliRunner56from terminating import tutorial003 as mod78runner = CliRunner()910app = typer.Typer()11app.command()(mod.main)121314def test_cli():15 result = runner.invoke(app, ["Camila"])16 assert result.exit_code == 017 assert "New user created: Camila" in result.output181920def 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.output252627def 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.stdout
modified:typer/__init__.py+1 added
25 unmodified lines
26 get_text_stream,27 open_file,28)2930from . import colors # noqa31from .main import Typer, run # noqa32from .models import ( # noqa33 Context,34 FileBinaryRead,
5 unmodified lines
added:typer/colors.py+20 added
1# Variable names to colors, just for completion2BLACK = "black"3RED = "red"4GREEN = "green"5YELLOW = "yellow"6BLUE = "blue"7MAGENTA = "magenta"8CYAN = "cyan"9WHITE = "white"1011RESET = "reset"1213BRIGHT_BLACK = "bright_black"14BRIGHT_RED = "bright_red"15BRIGHT_GREEN = "bright_green"16BRIGHT_YELLOW = "bright_yellow"17BRIGHT_BLUE = "bright_blue"18BRIGHT_MAGENTA = "bright_magenta"19BRIGHT_CYAN = "bright_cyan"20BRIGHT_WHITE = "bright_white"
modified:mkdocs.yml+2 added
21 unmodified lines
22 - 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