As the question says, I want to pretty print a dictionary such as locals()
but in a Panel object (surrounding the dictionary in a nice rectangle).
On trying the naïve approach, i.e.,
from rich.panel import Panel
from rich import print
print(Panel(locals()))
I'd get NotRenderableError: Unable to render ...; A str, Segment or object with __rich_console__ method is required
The best I could do was convert the dictionary into a renderable
by digging the source-code.
from rich.console import Console
def do(x):
c = Console()
print(Panel(c._collect_renderables(x, sep='\n', end='')))
do(globals())
But all it did was print the keys in a box
╭───────────────╮
│ dataset_path │
│ layouts │
│ line_level │
│ n │
╰───────────────╯
Can anyone suggest the right document I must go through to accomplish this, and in general what is the right way to understand how to utilize rich
to its fullest?
It turned out to be simpler than what I thought..
from rich import print
from rich.panel import Panel
from rich.console import Console
from rich.text import Text
def print_box(x, title=None):
console = Console()
with console.capture() as capture:
console.print(x)
str_output = capture.get()
text = Text.from_ansi(str_output)
print(Panel(text, title=title, padding=2))
Text
object, and
╭───────────────────────────────────────── Inputs ──────────────────────────────────────────╮
│ │
│ │
│ {'dataset_path': '/tmp/', 'layouts': '0,1,2,3', 'line_level': False, 'n': None} │
│ │
│ │
╰───────────────────────────────────────────────────────────────────────────────────────────╯