How to integrate Rich with Python curses?

1.6k Views Asked by At

I'm thinking of creating a CLI app using python curses and rich libraries. As curses requires addstr method to print text to string, I'm unable to print using rich. Is it possible to integrate these two libraries?

Following codes don't work accordingly!!

import curses
from curses import wrapper
from rich.console import Console
console = Console()
with console.capture() as capture:
    console.print("[bold red]Hello[/] World")
str_output = capture.get()

def main(stdscr):
    stdscr.clear()
    stdscr.addstr(str_output)
    stdscr.refresh()
    stdscr.getch()

wrapper(main)
2

There are 2 best solutions below

0
On BEST ANSWER

Author of Rich here. Rich and Curses probably aren't going to work well in combination. However you could look in to Textual which is a TUI framework I'm working on that uses Rich under the hood.

2
On

It seems you want to pipe the content from rich to curses but the print() function is not actually returning anything it is simply creating output on the terminal as a side effect of executing.

You can verify by looking at type(print("[red]Hello[/red] World!")) which is <class 'NoneType'>.

So, how can you retrieve the output from the print(...) ? In the docs for rich they explain how this can be done with the Console API:

from rich.console import Console
console = Console()
with console.capture() as capture:
    console.print("[bold red]Hello[/] World")

str_output = capture.get()


>>> str_output
'\x1b[1;31mHello\x1b[0m World\n'
>>> print(str_output)
Hello World

>>> type(str_output)
<class 'str'>

Which allows you to access the output from the print and you can then try to pipe that information to curses. You may run into some strange interferences from mixing curses and rich if you are overlapping their color contexts because of how color escape codes work in shells so be aware of that.