Search code examples
pythonrich

How can I put a table inside a layout box using Rich in Python?


This is code I am using to put a table inside the layout. However, in the output I am getting lot of ansii code-like characters, and even though I have defined the colour attribute for the column, in the output it is not appearing.

from re import X
import psycopg2
from rich.console import Console
from rich.table import Table
from rich import box
from rich.layout import Layout
from rich import print as rprint

layout = Layout()
layout.split_column(
    Layout(name="upper"),
    Layout(name="lower")
)

connection = psycopg2.connect(user="enterprisedb",
                                  password="xxxx",
                                  host="xx.xx.xxx.170",
                                  port="5444",
                                  database="edb")
cursor = connection.cursor()
def imp_file_layout():
    table1 = Table(title="FILE LOCATIONS")
    table1.add_column("FILE_NAME", style="cyan", no_wrap=True)
    table1.add_column("LOCATION", style="magenta")
    directory_detail_Query = "select name,setting from pg_settings where name in ('data_directory','config_file','hba_file');"
    cursor.execute(directory_detail_Query)
    directory_records = cursor.fetchall()
    for row in directory_records:
        table1.add_row(*list(row))
    console=Console(markup=False)
    with console.capture() as capture:
        console.print(table1)
    return capture.get()


x=imp_file_layout();
layout["lower"].update(x)

rprint(layout)

cursor.close()
connection.close()

OUTPUT:

╰───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────╯
[3m                      FILE LOCATIONS                       [0m
┏━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃[1m [0m[1mFILE_NAME     [0m[1m [0m┃[1m [0m[1mLOCATION                              [0m[1m [0m┃
┡━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┩
│[36m [0m[36mconfig_file   [0m[36m [0m│[35m [0m[35m/var/lib/edb/as14/data/postgresql.conf[0m[35m [0m│
│[36m [0m[36mdata_directory[0m[36m [0m│[35m [0m[35m/var/lib/edb/as14/data                [0m[35m [0m│
│[36m [0m[36mhba_file      [0m[36m [0m│[35m [0m[35m/var/lib/edb/as14/data/pg_hba.conf    [0m[35m [0m│
└────────────────┴────────────────────────────────────────┘

Is there any solution for this?

If I just do a normal print of the table, the output is coming as expected, but when I am trying to put it inside a layout placeholder, a lot of additional characters are appearing.


Solution

  • No need to capture the output of the Table. Return the Table instance and add it to your layout.