move example apps, add render_lines to scrollview

This commit is contained in:
Will McGugan
2022-06-08 16:19:17 +01:00
parent b9e1022f6e
commit 53693e6200
20 changed files with 45 additions and 1163 deletions

View File

@@ -1,9 +1,10 @@
# Examples
# Textual Examples
Run any of these examples to demonstrate a Textual features.
This directory contains example Textual applications.
The example code will generate a log file called "textual.log". Tail this file to gain insight in to what Textual is doing.
To run them, navigate to the examples directory and enter `python` followed buy the name of the Python file.
```
tail -f textual
cd textual/examples
python pride.py
```

View File

@@ -1,38 +0,0 @@
from textual.app import App
from textual.reactive import Reactive
from textual.widgets import Footer, Placeholder
class SmoothApp(App):
"""Demonstrates smooth animation. Press 'b' to see it in action."""
async def on_load(self) -> None:
"""Bind keys here."""
await self.bind("b", "toggle_sidebar", "Toggle sidebar")
await self.bind("q", "quit", "Quit")
show_bar = Reactive(False)
def watch_show_bar(self, show_bar: bool) -> None:
"""Called when show_bar changes."""
self.bar.animate("layout_offset_x", 0 if show_bar else -40)
def action_toggle_sidebar(self) -> None:
"""Called when user hits 'b' key."""
self.show_bar = not self.show_bar
async def on_mount(self) -> None:
"""Build layout here."""
footer = Footer()
self.bar = Placeholder(name="left")
await self.screen.dock(footer, edge="bottom")
await self.screen.dock(Placeholder(), Placeholder(), edge="top")
await self.screen.dock(self.bar, edge="left", size=40, z=1)
self.bar.layout_offset_x = -40
# self.set_timer(10, lambda: self.action("quit"))
SmoothApp.run(log_path="textual.log", log_verbosity=2)

View File

@@ -1,33 +0,0 @@
from rich.table import Table
from textual import events
from textual.app import App
from textual.widgets import ScrollView
class MyApp(App):
"""An example of a very simple Textual App"""
async def on_load(self, event: events.Load) -> None:
await self.bind("q", "quit", "Quit")
async def on_mount(self, event: events.Mount) -> None:
self.body = body = ScrollView(auto_width=True)
await self.screen.dock(body)
async def add_content():
table = Table(title="Demo")
for i in range(20):
table.add_column(f"Col {i + 1}", style="magenta")
for i in range(100):
table.add_row(*[f"cell {i},{j}" for j in range(20)])
await body.update(table)
await self.call_later(add_content)
MyApp.run(title="Simple App", log_path="textual.log")

View File

@@ -1,59 +0,0 @@
Screen {
/* text-background: #212121; */
}
#borders {
layout: vertical;
background: #212121;
overflow-y: scroll;
}
Lorem.border {
height: 12;
margin: 2 4;
background: #303f9f;
}
Lorem.round {
border: round #8bc34a;
}
Lorem.solid {
border: solid #8bc34a;
}
Lorem.double {
border: double #8bc34a;
}
Lorem.dashed {
border: dashed #8bc34a;
}
Lorem.heavy {
border: heavy #8bc34a;
}
Lorem.inner {
border: inner #8bc34a;
}
Lorem.outer {
border: outer #8bc34a;
}
Lorem.hkey {
border: hkey #8bc34a;
}
Lorem.vkey {
border: vkey #8bc34a;
}
Lorem.tall {
border: tall #8bc34a;
}
Lorem.wide {
border: wide #8bc34a;
}

View File

@@ -1,57 +0,0 @@
from rich.padding import Padding
from rich.style import Style
from rich.text import Text
from textual.app import App
from textual.renderables.gradient import VerticalGradient
from textual.widget import Widget
lorem = Text.from_markup(
"""[#C5CAE9]Lorem ipsum dolor sit amet, consectetur adipiscing elit. In velit libero, volutpat nec hendrerit at, faucibus in odio. Aliquam hendrerit nibh sed quam volutpat maximus. Nullam suscipit convallis lorem quis sodales. In tristique lobortis ante et dictum. Ut at finibus ipsum. In urna dolor, placerat et mi facilisis, congue sollicitudin massa. Phasellus felis turpis, cursus eu lectus et, porttitor malesuada augue. Sed feugiat volutpat velit, sollicitudin fringilla velit bibendum faucibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In velit libero, volutpat nec hendrerit at, faucibus in odio. Aliquam hendrerit nibh sed quam volutpat maximus. Nullam suscipit convallis lorem quis sodales. In tristique lobortis ante et dictum. Ut at finibus ipsum. In urna dolor, placerat et mi facilisis, congue sollicitudin massa. Phasellus felis turpis, cursus eu lectus et, porttitor malesuada augue. Sed feugiat volutpat velit, sollicitudin fringilla velit bibendum faucibus. """,
justify="full",
)
class Lorem(Widget):
def render(self) -> Text:
return Padding(lorem, 1)
class Background(Widget):
def render(self):
return VerticalGradient("#212121", "#212121")
class BordersApp(App):
"""Sandbox application used for testing/development by Textual developers"""
def on_load(self):
self.bind("q", "quit", "Quit")
def on_mount(self):
"""Build layout here."""
borders = [
Lorem(classes={"border", border})
for border in (
"round",
"solid",
"double",
"dashed",
"heavy",
"inner",
"outer",
"hkey",
"vkey",
"tall",
"wide",
)
]
borders_view = Background(*borders)
borders_view.show_vertical_scrollbar = True
self.mount(borders=borders_view)
app = BordersApp(css_path="borders.css", log_path="textual.log")
app.run()

View File

@@ -1,216 +0,0 @@
"""
A Textual app to create a fully working calculator, modelled after MacOS Calculator.
"""
from decimal import Decimal
from rich.align import Align
from rich.console import Console, ConsoleOptions, RenderResult, RenderableType
from rich.padding import Padding
from rich.style import Style
from rich.text import Text
from textual.app import App
from textual.reactive import Reactive
from textual.views import GridView
from textual.widget import Widget
from textual.widgets import Button
try:
from pyfiglet import Figlet
except ImportError:
print("Please install pyfiglet to run this example")
raise
class FigletText:
"""A renderable to generate figlet text that adapts to fit the container."""
def __init__(self, text: str) -> None:
self.text = text
def __rich_console__(
self, console: Console, options: ConsoleOptions
) -> RenderResult:
"""Build a Rich renderable to render the Figlet text."""
size = min(options.max_width / 2, options.max_height)
if size < 4:
yield Text(self.text, style="bold")
else:
if size < 7:
font_name = "mini"
elif size < 8:
font_name = "small"
elif size < 10:
font_name = "standard"
else:
font_name = "big"
font = Figlet(font=font_name, width=options.max_width)
yield Text(font.renderText(self.text).rstrip("\n"), style="bold")
class Numbers(Widget):
"""The digital display of the calculator."""
value = Reactive("0")
def render(self) -> RenderableType:
"""Build a Rich renderable to render the calculator display."""
return Padding(
Align.right(FigletText(self.value), vertical="middle"),
(0, 1),
style="white on rgb(51,51,51)",
)
class Calculator(GridView):
"""A working calculator app."""
DARK = "white on rgb(51,51,51)"
LIGHT = "black on rgb(165,165,165)"
YELLOW = "white on rgb(255,159,7)"
BUTTON_STYLES = {
"AC": LIGHT,
"C": LIGHT,
"+/-": LIGHT,
"%": LIGHT,
"/": YELLOW,
"X": YELLOW,
"-": YELLOW,
"+": YELLOW,
"=": YELLOW,
}
display = Reactive("0")
show_ac = Reactive(True)
def watch_display(self, value: str) -> None:
"""Called when self.display is modified."""
# self.numbers is a widget that displays the calculator result
# Setting the attribute value changes the display
# This allows us to write self.display = "100" to update the display
self.numbers.value = value
def compute_show_ac(self) -> bool:
"""Compute show_ac reactive value."""
# Condition to show AC button over C
return self.value in ("", "0") and self.display == "0"
def watch_show_ac(self, show_ac: bool) -> None:
"""When the show_ac attribute change we need to update the buttons."""
# Show AC and hide C or vice versa
self.c.display = not show_ac
self.ac.display = show_ac
def on_mount(self) -> None:
"""Event when widget is first mounted (added to a parent view)."""
# Attributes to store the current calculation
self.left = Decimal("0")
self.right = Decimal("0")
self.value = ""
self.operator = "+"
# The calculator display
self.numbers = Numbers()
self.numbers.style_border = "bold"
def make_button(text: str, style: str) -> Button:
"""Create a button with the given Figlet label."""
return Button(FigletText(text), style=style, name=text)
# Make all the buttons
self.buttons = {
name: make_button(name, self.BUTTON_STYLES.get(name, self.DARK))
for name in "+/-,%,/,7,8,9,X,4,5,6,-,1,2,3,+,.,=".split(",")
}
# Buttons that have to be treated specially
self.zero = make_button("0", self.DARK)
self.ac = make_button("AC", self.LIGHT)
self.c = make_button("C", self.LIGHT)
self.c.display = False
# Set basic grid settings
self.grid.set_gap(2, 1)
self.grid.set_gutter(1)
self.grid.set_align("center", "center")
# Create rows / columns / areas
self.grid.add_column("col", max_size=30, repeat=4)
self.grid.add_row("numbers", max_size=15)
self.grid.add_row("row", max_size=15, repeat=5)
self.grid.add_areas(
clear="col1,row1",
numbers="col1-start|col4-end,numbers",
zero="col1-start|col2-end,row5",
)
# Place out widgets in to the layout
self.grid.place(clear=self.c)
self.grid.place(
*self.buttons.values(), clear=self.ac, numbers=self.numbers, zero=self.zero
)
def handle_button_pressed(self, message: ButtonPressed) -> None:
"""A message sent by the button widget"""
assert isinstance(message.sender, Button)
button_name = message.sender.name
def do_math() -> None:
"""Does the math: LEFT OPERATOR RIGHT"""
self.log(self.left, self.operator, self.right)
try:
if self.operator == "+":
self.left += self.right
elif self.operator == "-":
self.left -= self.right
elif self.operator == "/":
self.left /= self.right
elif self.operator == "X":
self.left *= self.right
self.display = str(self.left)
self.value = ""
self.log("=", self.left)
except Exception:
self.display = "Error"
if button_name.isdigit():
self.display = self.value = self.value.lstrip("0") + button_name
elif button_name == "+/-":
self.display = self.value = str(Decimal(self.value or "0") * -1)
elif button_name == "%":
self.display = self.value = str(Decimal(self.value or "0") / Decimal(100))
elif button_name == ".":
if "." not in self.value:
self.display = self.value = (self.value or "0") + "."
elif button_name == "AC":
self.value = ""
self.left = self.right = Decimal(0)
self.operator = "+"
self.display = "0"
elif button_name == "C":
self.value = ""
self.display = "0"
elif button_name in ("+", "-", "/", "X"):
self.right = Decimal(self.value or "0")
do_math()
self.operator = button_name
elif button_name == "=":
if self.value:
self.right = Decimal(self.value)
do_math()
class CalculatorApp(App):
"""The Calculator Application"""
async def on_mount(self) -> None:
"""Mount the calculator widget."""
await self.screen.dock(Calculator())
CalculatorApp.run(title="Calculator Test", log_path="textual.log")

View File

@@ -1,70 +0,0 @@
import os
import sys
from rich.console import RenderableType
from rich.syntax import Syntax
from rich.traceback import Traceback
from textual.app import App
from textual.widgets import Header, Footer, FileClick, ScrollView, DirectoryTree
class MyApp(App):
"""An example of a very simple Textual App"""
async def on_load(self) -> None:
"""Sent before going in to application mode."""
# Bind our basic keys
await self.bind("b", "view.toggle('sidebar')", "Toggle sidebar")
await self.bind("q", "quit", "Quit")
# Get path to show
try:
self.path = sys.argv[1]
except IndexError:
self.path = os.path.abspath(
os.path.join(os.path.basename(__file__), "../../")
)
async def on_mount(self) -> None:
"""Call after terminal goes in to application mode"""
# Create our widgets
# In this a scroll view for the code and a directory tree
self.body = ScrollView()
self.directory = DirectoryTree(self.path, "Code")
# Dock our widgets
await self.screen.dock(Header(), edge="top")
await self.screen.dock(Footer(), edge="bottom")
# Note the directory is also in a scroll view
await self.screen.dock(
ScrollView(self.directory), edge="left", size=48, name="sidebar"
)
await self.screen.dock(self.body, edge="top")
async def handle_file_click(self, message: FileClick) -> None:
"""A message sent by the directory tree when a file is clicked."""
syntax: RenderableType
try:
# Construct a Syntax object for the path in the message
syntax = Syntax.from_path(
message.path,
line_numbers=True,
word_wrap=True,
indent_guides=True,
theme="monokai",
)
except Exception:
# Possibly a binary file
# For demonstration purposes we will show the traceback
syntax = Traceback(theme="monokai", width=None, show_locals=True)
self.app.sub_title = os.path.basename(message.path)
await self.body.update(syntax)
# Run our app class
MyApp.run(title="Code Viewer", log_path="textual.log")

View File

@@ -1,10 +0,0 @@
header blue white on #173f5f
sidebar #09312e on #3caea3
sidebar border #09312e
content blue white #20639b
content border #0f2b41
footer border #0f2b41
footer yellow #3a3009 on #f6d55c;

View File

@@ -1,45 +0,0 @@
from textual._easing import EASING
from textual.app import App
from textual.reactive import Reactive
from textual.views import DockView
from textual.widgets import Placeholder, TreeControl, ScrollView, TreeClick
class EasingApp(App):
"""An app do demonstrate easing."""
side = Reactive(False)
easing = Reactive("linear")
def watch_side(self, side: bool) -> None:
"""Animate when the side changes (False for left, True for right)."""
width = self.easing_view.size.width
animate_x = (width - self.placeholder.size.width) if side else 0
self.placeholder.animate(
"layout_offset_x", animate_x, easing=self.easing, duration=1
)
async def on_mount(self) -> None:
"""Called when application mode is ready."""
self.placeholder = Placeholder()
self.easing_view = DockView()
self.placeholder.style = "white on dark_blue"
tree = TreeControl("Easing", {})
for easing_key in sorted(EASING.keys()):
await tree.add(tree.root.id, easing_key, {"easing": easing_key})
await tree.root.expand()
await self.screen.dock(ScrollView(tree), edge="left", size=32)
await self.screen.dock(self.easing_view)
await self.easing_view.dock(self.placeholder, edge="left", size=32)
async def handle_tree_click(self, message: TreeClick[dict]) -> None:
"""Called in response to a tree click."""
self.easing = message.node.data.get("easing", "linear")
self.side = not self.side
EasingApp().run(log_path="textual.log")

View File

@@ -1,34 +0,0 @@
App > View {
layout: dock;
docks: side=left/1;
}
#header {
text: on #173f5f;
height: 3;
border: hkey white;
}
#content {
text: on #20639b;
}
#footer {
height: 3;
border-top: hkey #0f2b41;
text: #3a3009 on #f6d55c;
}
#sidebar {
text: #09312e on #3caea3;
dock: side;
width: 30;
border-right: outer #09312e;
offset-x: -100%;
transition: offset 400ms in_out_cubic;
}
#sidebar.-active {
offset-x: 0;
transition: offset 400ms in_out_cubic;
}

View File

@@ -1,34 +0,0 @@
from textual.app import App
from textual.widgets import Placeholder
class GridTest(App):
async def on_mount(self) -> None:
"""Make a simple grid arrangement."""
grid = await self.screen.dock_grid(edge="left", name="left")
grid.add_column(fraction=1, name="left", min_size=20)
grid.add_column(size=30, name="center")
grid.add_column(fraction=1, name="right")
grid.add_row(fraction=1, name="top", min_size=2)
grid.add_row(fraction=2, name="middle")
grid.add_row(fraction=1, name="bottom")
grid.add_areas(
area1="left,top",
area2="center,middle",
area3="left-start|right-end,bottom",
area4="right,top-start|middle-end",
)
grid.place(
area1=Placeholder(name="area1"),
area2=Placeholder(name="area2"),
area3=Placeholder(name="area3"),
area4=Placeholder(name="area4"),
)
GridTest.run(title="Grid Test", log_path="textual.log")

View File

@@ -1,22 +0,0 @@
from textual.app import App
from textual import events
from textual.widgets import Placeholder
class GridTest(App):
async def on_mount(self, event: events.Mount) -> None:
"""Create a grid with auto-arranging cells."""
grid = await self.screen.dock_grid()
grid.add_column("col", fraction=1, max_size=20)
grid.add_row("row", fraction=1, max_size=10)
grid.set_repeat(True, True)
grid.add_areas(center="col-2-start|col-4-end,row-2-start|row-3-end")
grid.set_align("stretch", "center")
placeholders = [Placeholder() for _ in range(20)]
grid.place(*placeholders, center=Placeholder())
GridTest.run(title="Grid Test", log_path="textual.log")

View File

@@ -1,444 +0,0 @@
[![Downloads](https://pepy.tech/badge/rich/month)](https://pepy.tech/project/rich)
[![PyPI version](https://badge.fury.io/py/rich.svg)](https://badge.fury.io/py/rich)
[![codecov](https://codecov.io/gh/willmcgugan/rich/branch/master/graph/badge.svg)](https://codecov.io/gh/willmcgugan/rich)
[![Rich blog](https://img.shields.io/badge/blog-rich%20news-yellowgreen)](https://www.willmcgugan.com/tag/rich/)
[![Twitter Follow](https://img.shields.io/twitter/follow/willmcgugan.svg?style=social)](https://twitter.com/willmcgugan)
![Logo](https://github.com/willmcgugan/rich/raw/master/imgs/logo.svg)
[中文 readme](https://github.com/willmcgugan/rich/blob/master/README.cn.md) • [Lengua española readme](https://github.com/willmcgugan/rich/blob/master/README.es.md) • [Deutsche readme](https://github.com/willmcgugan/rich/blob/master/README.de.md) • [Läs på svenska](https://github.com/willmcgugan/rich/blob/master/README.sv.md) • [日本語 readme](https://github.com/willmcgugan/rich/blob/master/README.ja.md) • [한국어 readme](https://github.com/willmcgugan/rich/blob/master/README.kr.md)
Rich is a Python library for _rich_ text and beautiful formatting in the terminal.
The [Rich API](https://rich.readthedocs.io/en/latest/) makes it easy to add color and style to terminal output. Rich can also render pretty tables, progress bars, markdown, syntax highlighted source code, tracebacks, and more — out of the box.
![Features](https://github.com/willmcgugan/rich/raw/master/imgs/features.png)
For a video introduction to Rich see [calmcode.io](https://calmcode.io/rich/introduction.html) by [@fishnets88](https://twitter.com/fishnets88).
See what [people are saying about Rich](https://www.willmcgugan.com/blog/pages/post/rich-tweets/).
## Compatibility
Rich works with Linux, OSX, and Windows. True color / emoji works with new Windows Terminal, classic terminal is limited to 16 colors. Rich requires Python 3.6.1 or later.
Rich works with [Jupyter notebooks](https://jupyter.org/) with no additional configuration required.
## Installing
Install with `pip` or your favorite PyPi package manager.
```
pip install rich
```
Run the following to test Rich output on your terminal:
```
python -m rich
```
## Rich Print
To effortlessly add rich output to your application, you can import the [rich print](https://rich.readthedocs.io/en/latest/introduction.html#quick-start) method, which has the same signature as the builtin Python function. Try this:
```python
from rich import print
print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals())
```
![Hello World](https://github.com/willmcgugan/rich/raw/master/imgs/print.png)
## Rich REPL
Rich can be installed in the Python REPL, so that any data structures will be pretty printed and highlighted.
```python
>>> from rich import pretty
>>> pretty.install()
```
![REPL](https://github.com/willmcgugan/rich/raw/master/imgs/repl.png)
## Using the Console
For more control over rich terminal content, import and construct a [Console](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console) object.
```python
from rich.console import Console
console = Console()
```
The Console object has a `print` method which has an intentionally similar interface to the builtin `print` function. Here's an example of use:
```python
console.print("Hello", "World!")
```
As you might expect, this will print `"Hello World!"` to the terminal. Note that unlike the builtin `print` function, Rich will word-wrap your text to fit within the terminal width.
There are a few ways of adding color and style to your output. You can set a style for the entire output by adding a `style` keyword argument. Here's an example:
```python
console.print("Hello", "World!", style="bold red")
```
The output will be something like the following:
![Hello World](https://github.com/willmcgugan/rich/raw/master/imgs/hello_world.png)
That's fine for styling a line of text at a time. For more finely grained styling, Rich renders a special markup which is similar in syntax to [bbcode](https://en.wikipedia.org/wiki/BBCode). Here's an example:
```python
console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].")
```
![Console Markup](https://github.com/willmcgugan/rich/raw/master/imgs/where_there_is_a_will.png)
You can use a Console object to generate sophisticated output with minimal effort. See the [Console API](https://rich.readthedocs.io/en/latest/console.html) docs for details.
## Rich Inspect
Rich has an [inspect](https://rich.readthedocs.io/en/latest/reference/init.html?highlight=inspect#rich.inspect) function which can produce a report on any Python object, such as class, instance, or builtin.
```python
>>> my_list = ["foo", "bar"]
>>> from rich import inspect
>>> inspect(my_list, methods=True)
```
![Log](https://github.com/willmcgugan/rich/raw/master/imgs/inspect.png)
See the [inspect docs](https://rich.readthedocs.io/en/latest/reference/init.html#rich.inspect) for details.
# Rich Library
Rich contains a number of builtin _renderables_ you can use to create elegant output in your CLI and help you debug your code.
Click the following headings for details:
<details>
<summary>Log</summary>
The Console object has a `log()` method which has a similar interface to `print()`, but also renders a column for the current time and the file and line which made the call. By default Rich will do syntax highlighting for Python structures and for repr strings. If you log a collection (i.e. a dict or a list) Rich will pretty print it so that it fits in the available space. Here's an example of some of these features.
```python
from rich.console import Console
console = Console()
test_data = [
{"jsonrpc": "2.0", "method": "sum", "params": [None, 1, 2, 4, False, True], "id": "1",},
{"jsonrpc": "2.0", "method": "notify_hello", "params": [7]},
{"jsonrpc": "2.0", "method": "subtract", "params": [42, 23], "id": "2"},
]
def test_log():
enabled = False
context = {
"foo": "bar",
}
movies = ["Deadpool", "Rise of the Skywalker"]
console.log("Hello from", console, "!")
console.log(test_data, log_locals=True)
test_log()
```
The above produces the following output:
![Log](https://github.com/willmcgugan/rich/raw/master/imgs/log.png)
Note the `log_locals` argument, which outputs a table containing the local variables where the log method was called.
The log method could be used for logging to the terminal for long running applications such as servers, but is also a very nice debugging aid.
</details>
<details>
<summary>Logging Handler</summary>
You can also use the builtin [Handler class](https://rich.readthedocs.io/en/latest/logging.html) to format and colorize output from Python's logging module. Here's an example of the output:
![Logging](https://github.com/willmcgugan/rich/raw/master/imgs/logging.png)
</details>
<details>
<summary>Emoji</summary>
To insert an emoji in to console output place the name between two colons. Here's an example:
```python
>>> console.print(":smiley: :vampire: :pile_of_poo: :thumbs_up: :raccoon:")
😃 🧛 💩 👍 🦝
```
Please use this feature wisely.
</details>
<details>
<summary>Tables</summary>
Rich can render flexible [tables](https://rich.readthedocs.io/en/latest/tables.html) with unicode box characters. There is a large variety of formatting options for borders, styles, cell alignment etc.
![table movie](https://github.com/willmcgugan/rich/raw/master/imgs/table_movie.gif)
The animation above was generated with [table_movie.py](https://github.com/willmcgugan/rich/blob/master/examples/table_movie.py) in the examples directory.
Here's a simpler table example:
```python
from rich.console import Console
from rich.table import Table
console = Console()
table = Table(show_header=True, header_style="bold magenta")
table.add_column("Date", style="dim", width=12)
table.add_column("Title")
table.add_column("Production Budget", justify="right")
table.add_column("Box Office", justify="right")
table.add_row(
"Dev 20, 2019", "Star Wars: The Rise of Skywalker", "$275,000,000", "$375,126,118"
)
table.add_row(
"May 25, 2018",
"[red]Solo[/red]: A Star Wars Story",
"$275,000,000",
"$393,151,347",
)
table.add_row(
"Dec 15, 2017",
"Star Wars Ep. VIII: The Last Jedi",
"$262,000,000",
"[bold]$1,332,539,889[/bold]",
)
console.print(table)
```
This produces the following output:
![table](https://github.com/willmcgugan/rich/raw/master/imgs/table.png)
Note that console markup is rendered in the same way as `print()` and `log()`. In fact, anything that is renderable by Rich may be included in the headers / rows (even other tables).
The `Table` class is smart enough to resize columns to fit the available width of the terminal, wrapping text as required. Here's the same example, with the terminal made smaller than the table above:
![table2](https://github.com/willmcgugan/rich/raw/master/imgs/table2.png)
</details>
<details>
<summary>Progress Bars</summary>
Rich can render multiple flicker-free [progress](https://rich.readthedocs.io/en/latest/progress.html) bars to track long-running tasks.
For basic usage, wrap any sequence in the `track` function and iterate over the result. Here's an example:
```python
from rich.progress import track
for step in track(range(100)):
do_step(step)
```
It's not much harder to add multiple progress bars. Here's an example taken from the docs:
![progress](https://github.com/willmcgugan/rich/raw/master/imgs/progress.gif)
The columns may be configured to show any details you want. Built-in columns include percentage complete, file size, file speed, and time remaining. Here's another example showing a download in progress:
![progress](https://github.com/willmcgugan/rich/raw/master/imgs/downloader.gif)
To try this out yourself, see [examples/downloader.py](https://github.com/willmcgugan/rich/blob/master/examples/downloader.py) which can download multiple URLs simultaneously while displaying progress.
</details>
<details>
<summary>Status</summary>
For situations where it is hard to calculate progress, you can use the [status](https://rich.readthedocs.io/en/latest/reference/console.html#rich.console.Console.status) method which will display a 'spinner' animation and message. The animation won't prevent you from using the console as normal. Here's an example:
```python
from time import sleep
from rich.console import Console
console = Console()
tasks = [f"task {n}" for n in range(1, 11)]
with console.status("[bold green]Working on tasks...") as status:
while tasks:
task = tasks.pop(0)
sleep(1)
console.log(f"{task} complete")
```
This generates the following output in the terminal.
![status](https://github.com/willmcgugan/rich/raw/master/imgs/status.gif)
The spinner animations were borrowed from [cli-spinners](https://www.npmjs.com/package/cli-spinners). You can select a spinner by specifying the `spinner` parameter. Run the following command to see the available values:
```
python -m rich.spinner
```
The above command generate the following output in the terminal:
![spinners](https://github.com/willmcgugan/rich/raw/master/imgs/spinners.gif)
</details>
<details>
<summary>Tree</summary>
Rich can render a [tree](https://rich.readthedocs.io/en/latest/tree.html) with guide lines. A tree is ideal for displaying a file structure, or any other hierarchical data.
The labels of the tree can be simple text or anything else Rich can render. Run the following for a demonstration:
```
python -m rich.tree
```
This generates the following output:
![markdown](https://github.com/willmcgugan/rich/raw/master/imgs/tree.png)
See the [tree.py](https://github.com/willmcgugan/rich/blob/master/examples/tree.py) example for a script that displays a tree view of any directory, similar to the linux `tree` command.
</details>
<details>
<summary>Columns</summary>
Rich can render content in neat [columns](https://rich.readthedocs.io/en/latest/columns.html) with equal or optimal width. Here's a very basic clone of the (MacOS / Linux) `ls` command which displays a directory listing in columns:
```python
import os
import sys
from rich import print
from rich.columns import Columns
directory = os.listdir(sys.argv[1])
print(Columns(directory))
```
The following screenshot is the output from the [columns example](https://github.com/willmcgugan/rich/blob/master/examples/columns.py) which displays data pulled from an API in columns:
![columns](https://github.com/willmcgugan/rich/raw/master/imgs/columns.png)
</details>
<details>
<summary>Markdown</summary>
Rich can render [markdown](https://rich.readthedocs.io/en/latest/markdown.html) and does a reasonable job of translating the formatting to the terminal.
To render markdown import the `Markdown` class and construct it with a string containing markdown code. Then print it to the console. Here's an example:
```python
from rich.console import Console
from rich.markdown import Markdown
console = Console()
with open("README.md") as readme:
markdown = Markdown(readme.read())
console.print(markdown)
```
This will produce output something like the following:
![markdown](https://github.com/willmcgugan/rich/raw/master/imgs/markdown.png)
</details>
<details>
<summary>Syntax Highlighting</summary>
Rich uses the [pygments](https://pygments.org/) library to implement [syntax highlighting](https://rich.readthedocs.io/en/latest/syntax.html). Usage is similar to rendering markdown; construct a `Syntax` object and print it to the console. Here's an example:
```python
from rich.console import Console
from rich.syntax import Syntax
my_code = '''
def iter_first_last(values: Iterable[T]) -> Iterable[Tuple[bool, bool, T]]:
"""Iterate and generate a tuple with a flag for first and last value."""
iter_values = iter(values)
try:
previous_value = next(iter_values)
except StopIteration:
return
first = True
for value in iter_values:
yield first, False, previous_value
first = False
previous_value = value
yield first, True, previous_value
'''
syntax = Syntax(my_code, "python", theme="monokai", line_numbers=True)
console = Console()
console.print(syntax)
```
This will produce the following output:
![syntax](https://github.com/willmcgugan/rich/raw/master/imgs/syntax.png)
</details>
<details>
<summary>Tracebacks</summary>
Rich can render [beautiful tracebacks](https://rich.readthedocs.io/en/latest/traceback.html) which are easier to read and show more code than standard Python tracebacks. You can set Rich as the default traceback handler so all uncaught exceptions will be rendered by Rich.
Here's what it looks like on OSX (similar on Linux):
![traceback](https://github.com/willmcgugan/rich/raw/master/imgs/traceback.png)
</details>
All Rich renderables make use of the [Console Protocol](https://rich.readthedocs.io/en/latest/protocol.html), which you can also use to implement your own Rich content.
# Rich for enterprise
Available as part of the Tidelift Subscription.
The maintainers of Rich and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source packages you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact packages you use. [Learn more.](https://tidelift.com/subscription/pkg/pypi-rich?utm_source=pypi-rich&utm_medium=referral&utm_campaign=enterprise&utm_term=repo)
# Project using Rich
Here are a few projects using Rich:
- [BrancoLab/BrainRender](https://github.com/BrancoLab/BrainRender)
a python package for the visualization of three dimensional neuro-anatomical data
- [Ciphey/Ciphey](https://github.com/Ciphey/Ciphey)
Automated decryption tool
- [emeryberger/scalene](https://github.com/emeryberger/scalene)
a high-performance, high-precision CPU and memory profiler for Python
- [hedythedev/StarCli](https://github.com/hedythedev/starcli)
Browse GitHub trending projects from your command line
- [intel/cve-bin-tool](https://github.com/intel/cve-bin-tool)
This tool scans for a number of common, vulnerable components (openssl, libpng, libxml2, expat and a few others) to let you know if your system includes common libraries with known vulnerabilities.
- [nf-core/tools](https://github.com/nf-core/tools)
Python package with helper tools for the nf-core community.
- [cansarigol/pdbr](https://github.com/cansarigol/pdbr)
pdb + Rich library for enhanced debugging
- [plant99/felicette](https://github.com/plant99/felicette)
Satellite imagery for dummies.
- [seleniumbase/SeleniumBase](https://github.com/seleniumbase/SeleniumBase)
Automate & test 10x faster with Selenium & pytest. Batteries included.
- [smacke/ffsubsync](https://github.com/smacke/ffsubsync)
Automagically synchronize subtitles with video.
- [tryolabs/norfair](https://github.com/tryolabs/norfair)
Lightweight Python library for adding real-time 2D object tracking to any detector.
- [ansible/ansible-lint](https://github.com/ansible/ansible-lint) Ansible-lint checks playbooks for practices and behaviour that could potentially be improved
- [ansible-community/molecule](https://github.com/ansible-community/molecule) Ansible Molecule testing framework
- +[Many more](https://github.com/willmcgugan/rich/network/dependents)!
<!-- This is a test, no need to translate -->

View File

@@ -1,51 +0,0 @@
from rich.markdown import Markdown
from textual.app import App
from textual.widgets import Header, Footer, Placeholder, ScrollView
class MyApp(App):
"""An example of a very simple Textual App"""
stylesheet = """
App > View {
layout: dock
}
#body {
padding: 1
}
#sidebar {
edge left
size: 40
}
"""
async def on_load(self) -> None:
"""Bind keys with the app loads (but before entering application mode)"""
await self.bind("b", "view.toggle('sidebar')", "Toggle sidebar")
await self.bind("q", "quit", "Quit")
async def on_mount(self) -> None:
"""Create and dock the widgets."""
body = ScrollView()
await self.screen.mount(
Header(),
Footer(),
body=body,
sidebar=Placeholder(),
)
async def get_markdown(filename: str) -> None:
with open(filename, "rt") as fh:
readme = Markdown(fh.read(), hyperlinks=True)
await body.update(readme)
await self.call_later(get_markdown, "richreadme.md")
MyApp.run(title="Simple App", log_path="textual.log")

View File

@@ -1,7 +0,0 @@
Header {
border: solid #122233;
}
App > View > Widget {
display: none;
}