Search code examples
pythonpython-3.xprintingpretty-printrich

How to print a dictionary in a `rich.panel.Panel` object?


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?


Solution

  • 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))
    
    1. Capture the text in a console output
    2. Convert it to Text object, and
    3. Display in a Panel
    
    ╭───────────────────────────────────────── Inputs ──────────────────────────────────────────╮
    │                                                                                           │
    │                                                                                           │
    │  {'dataset_path': '/tmp/', 'layouts': '0,1,2,3', 'line_level': False, 'n': None}          │
    │                                                                                           │
    │                                                                                           │
    ╰───────────────────────────────────────────────────────────────────────────────────────────╯