📝 Add docs for using Rich with Typer (#421)
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 · parent 85bc9bc · Browse files · 10 files·+195 added−36 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+195 added−36 removed
- other:+195 added−36 removed
Provenance
- Commit
33dcb53- Tree
f2a796a- Author
Sebastián Ramírez <tiangolo@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
85bc9bc
10 files changed+195 added−36 removed
modified:docs/tutorial/progressbar.md+99 added-10 removed
112334565789109111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310435 unmodified lines14014114214361144145146147148149150151152153681541551561571588 unmodified lines1671681691708517117217317417513 unmodified lines1891901911921071931941951961971981992001122012022032042059 unmodified lines2152162172181302192202212222235 unmodified linesIf you are executing an operation that can take some time, you can inform it to the user with a progress bar.If you are executing an operation that can take some time, you can inform it to the user. 🤓
For this, you can use `typer.progressbar()`:## Progress Bar
You can use <a href="https://rich.readthedocs.io/en/stable/progress.html" class="external-link" target="_blank">Rich's Progress Display</a> to show a progress bar, for example:
```Python hl_lines="8"```Python hl_lines="4 9"{!../docs_src/progressbar/tutorial001.py!}```
You use `typer.progressbar()` with a `with` statement, as in:You put the thing that you want to iterate over inside of Rich's `track()`, and then iterate over that.
Check it:
<div class="termy">
```console$ python main.py
---> 100%
Processed 100 things.```
</div>
...actually, it will look a lot prettier. ✨ But I can't show you the animation here in the docs. 😅
The colors and information will look something like this:
<div class="termy">
```console$ python main.py
Processing... <font color="#F92672">━━━━━━━━━━━━━━━━━━━━━━━━━━━━━╸</font><font color="#3A3A3A">━━━━━━━━━━</font> <font color="#AE81FF"> 74%</font> <font color="#A1EFE4">0:00:01</font>```
</div>
## Spinner
When you don't know how long the operation will take, you can use a spinner instead.
Rich allows you to display many things in complex and advanced ways.
For example, this will show two spinners:
```Python hl_lines="4 8-15"{!../docs_src/progressbar/tutorial002.py!}```
I can't show you the beautiful animation here in the docs. 😅
But at some point in time it will look like this (imagine it's spinning). 🤓
<div class="termy">
```console$ python main.py
<font color="#A6E22E">⠹</font> Processing...<font color="#A6E22E">⠹</font> Preparing...```
</div>
You can learn more about it in the <a href="https://rich.readthedocs.io/en/stable/progress.html" class="external-link" target="_blank">Rich docs for Progress Display</a>.
## Typer `progressbar`
If you can, you should use **Rich** as explained above, it has more features, it's more advanced, and can display information more beautifully. ✨
!!! tip If you can use Rich, use the information above, the Rich docs, and skip the rest of this page. 😎
But if you can't use Rich, Typer (actually Click) comes with a simple utility to show progress bars.
!!! info `typer.progressbar()` comes directly from Click, you can read more about it in <a href="https://click.palletsprojects.com/en/8.1.x/utils/#showing-progress-bars" class="external-link" target="_blank">Click's docs</a>.
### Use `typer.progressbar`
!!! tip Remember, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎
You can use `typer.progressbar()` with a `with` statement, as in:
```Pythonwith typer.progressbar(something) as progress: pass```
And you pass as function argument to `typer.progressbar()` the thing that you would normally iterate over.
```Python hl_lines="8"{!../docs_src/progressbar/tutorial003.py!}```
So, if you have a list of users, this could be:
```Pythonusers = ["Camila", "Rick", "Morty"]35 unmodified lines```
</div>
## Setting a Progress Bar `length`### Setting a Progress Bar `length`
!!! tip Remember, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎
The progress bar is generated from the length of the iterable (e.g. the list of users).
But if the length is not available (for example, with something that fetches a new user from a web API each time) you can pass an explicit `length` to `typer.progressbar()`.
```Python hl_lines="14"{!../docs_src/progressbar/tutorial002.py!}{!../docs_src/progressbar/tutorial004.py!}```
Check it:
8 unmodified lines```
</div>
### About the function with `yield`#### About the function with `yield`
If you hadn't seen something like that `yield` above, that's a "<a href="https://docs.python.org/3/glossary.html#term-generator" class="external-link" target="_blank">generator</a>".
You can iterate over that function with a `for` and at each iteration it will give you the value at `yield`.13 unmodified lines```
would print each of the "user IDs" (here it's just the numbers from `0` to `99`).
## Add a `label`### Add a `label`
!!! tip Remember, you are much better off using <a href="https://rich.readthedocs.io/" class="external-link" target="_blank">Rich</a> for this. 😎
You can also set a `label`:
```Python hl_lines="8"{!../docs_src/progressbar/tutorial003.py!}{!../docs_src/progressbar/tutorial005.py!}```
Check it:
9 unmodified lines
And then calling the `.update()` method in the object from the `with` statement:
```Python hl_lines="8 12"{!../docs_src/progressbar/tutorial004.py!}{!../docs_src/progressbar/tutorial006.py!}```
Check it:
5 unmodified linesmodified:docs/tutorial/prompt.md+22 added
74 unmodified lines75 Aborted!76 ```77 78 </div>79+80+## Prompt with Rich81+82+If you installed Rich as described in [Printing and Colors](printing.md){.internal-link target=_blank}, you can use Rich to prompt the user for input:83+84+```Python hl_lines="2 6"85+{!../docs_src/prompt/tutorial004.py!}86+```87+88+And when you run it, it will look like:89+90+<div class="termy">91+92+```console93+$ python main.py94+95+# Enter your name 😎:$ Morty96+97+Hello Morty98+```99+100+</div>modified:docs_src/progressbar/tutorial001.py+5 added-5 removed
1 import time2 3 import typer4+from rich.progress import track5 6 7 def main():8 total = 08- with typer.progressbar(range(100)) as progress:9- for value in progress:10- # Fake processing time11- time.sleep(0.01)12- total += 19+ for value in track(range(100), description="Processing..."):10+ # Fake processing time11+ time.sleep(0.01)12+ total += 113 print(f"Processed {total} things.")14 15 16 if __name__ == "__main__":1 unmodified linemodified:docs_src/progressbar/tutorial002.py+10 added-13 removed
1 import time2 3 import typer4+from rich.progress import Progress, SpinnerColumn, TextColumn5 6 6-def iterate_user_ids():7- # Let's imagine this is a web API, not a range()8- for i in range(100):9- yield i10-11-7 def main():13- total = 014- with typer.progressbar(iterate_user_ids(), length=100) as progress:15- for value in progress:16- # Fake processing time17- time.sleep(0.01)18- total += 119- print(f"Processed {total} user IDs.")8+ with Progress(9+ SpinnerColumn(),10+ TextColumn("[progress.description]{task.description}"),11+ transient=True,12+ ) as progress:13+ progress.add_task(description="Processing...", total=None)14+ progress.add_task(description="Preparing...", total=None)15+ time.sleep(5)16+ print("Done!")17 18 19 if __name__ == "__main__":20 typer.run(main)modified:docs_src/progressbar/tutorial003.py+1 added-1 removed
3 unmodified lines4 5 6 def main():7 total = 08- with typer.progressbar(range(100), label="Processing") as progress:8+ with typer.progressbar(range(100)) as progress:9 for value in progress:10 # Fake processing time11 time.sleep(0.01)12 total += 15 unmodified linesmodified:docs_src/progressbar/tutorial004.py+12 added-6 removed
1 unmodified line2 3 import typer4 5 6+def iterate_user_ids():7+ # Let's imagine this is a web API, not a range()8+ for i in range(100):9+ yield i10+11+12 def main():7- total = 10008- with typer.progressbar(length=total) as progress:9- for batch in range(4):13+ total = 014+ with typer.progressbar(iterate_user_ids(), length=100) as progress:15+ for value in progress:16 # Fake processing time11- time.sleep(1)12- progress.update(250)13- print(f"Processed {total} things in batches.")17+ time.sleep(0.01)18+ total += 119+ print(f"Processed {total} user IDs.")20 21 22 if __name__ == "__main__":23 typer.run(main)added:docs_src/progressbar/tutorial005.py+17 added
1+import time2+3+import typer4+5+6+def main():7+ total = 08+ with typer.progressbar(range(100), label="Processing") as progress:9+ for value in progress:10+ # Fake processing time11+ time.sleep(0.01)12+ total += 113+ print(f"Processed {total} things.")14+15+16+if __name__ == "__main__":17+ typer.run(main)added:docs_src/progressbar/tutorial006.py+17 added
1+import time2+3+import typer4+5+6+def main():7+ total = 10008+ with typer.progressbar(length=total) as progress:9+ for batch in range(4):10+ # Fake processing time11+ time.sleep(1)12+ progress.update(250)13+ print(f"Processed {total} things in batches.")14+15+16+if __name__ == "__main__":17+ typer.run(main)added:docs_src/prompt/tutorial004.py+11 added
1+import typer2+from rich.prompt import Prompt3+4+5+def main():6+ name = Prompt.ask("Enter your name :sunglasses:")7+ print(f"Hey there {name}!")8+9+10+if __name__ == "__main__":11+ typer.run(main)modified:.pre-commit-config.yaml+1 added-1 removed
17 unmodified lines18 args:19 - --py3-plus20 - --keep-runtime-typing21 # This file is more readable without yield from22- exclude: ^docs_src/progressbar/tutorial002\.py22+ exclude: ^docs_src/progressbar/tutorial004\.py23 - repo: https://github.com/myint/autoflake24 rev: v1.425 hooks:26 - id: autoflake27 unmodified lines