stephane.bio
  • Invest
  • Build
  • Write
  • Think
Ketchup

Textualize/rich: Rich is a Python library for rich text and beautiful formatting in the terminal.

URL
https://github.com/Textualize/rich
image
image
image
image
image
image
image

English readme • 简体中文 readme • 正體中文 readme • Lengua española readme • Deutsche readme • Läs på svenska • 日本語 readme • 한국어 readme • Français readme • Schwizerdütsch readme • हिन्दी readme • Português brasileiro readme • Italian readme • Русский readme • Indonesian readme • فارسی readme • Türkçe readme • Polskie readme

Rich is a Python library for rich text and beautiful formatting in the terminal.

The Rich API 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.

image

For a video introduction to Rich see calmcode.io by @fishnets88.

See what people are saying about Rich.

Compatibility

Rich works with Linux, macOS and Windows. True color / emoji works with new Windows Terminal, classic terminal is limited to 16 colors. Rich requires Python 3.7 or later.

Rich works with Jupyter notebooks with no additional configuration required.

Installing

Install with pip or your favorite PyPI package manager.

python -m 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 method, which has the same signature as the builtin Python function. Try this:

from rich import print

print("Hello, [bold magenta]World[/bold magenta]!", ":vampire:", locals())
image

Rich REPL

Rich can be installed in the Python REPL, so that any data structures will be pretty printed and highlighted.

>>> from rich import pretty
>>> pretty.install()
image

Using the Console

For more control over rich terminal content, import and construct a Console object.

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:

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:

console.print("Hello", "World!", style="bold red")

The output will be something like the following:

image

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. Here's an example:

console.print("Where there is a [bold cyan]Will[/bold cyan] there [u]is[/u] a [i]way[/i].")
image

You can use a Console object to generate sophisticated output with minimal effort. See the Console API docs for details.

Rich Inspect

Rich has an inspect function which can produce a report on any Python object, such as class, instance, or builtin.

>>> my_list = ["foo", "bar"]
>>> from rich import inspect
>>> inspect(my_list, methods=True)
image

See the inspect docs 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:

‣
Log
‣
Logging Handler
‣
Emoji
‣
Tables
‣
Progress Bars
‣
Status
‣
Tree
‣
Columns
‣
Markdown
‣
Syntax Highlighting
‣
Tracebacks

All Rich renderables make use of the Console Protocol, which you can also use to implement your own Rich content.

Rich CLI

See also Rich CLI for a command line application powered by Rich. Syntax highlight code, render markdown, display CSVs in tables, and more, directly from the command prompt.

image

Textual

See also Rich's sister project, Textual, which you can use to build sophisticated User Interfaces in the terminal.

image

Comments

bwalrond commented Jan 26, 2020

I'm really liking this library!

One thing ... I seem to be having trouble with tables with widths greater than 80 chars. Tried the various width options, but no luck. Thoughts?

Thanks.

Collaborator

willmcgugan commented Jan 26, 2020

What trouble are you having? Rich should detect the width of the terminal automatically. Post a screenshot if you like.

Author

bwalrond commented Jan 26, 2020

The table doesn't seem to expand beyond 80chars, instead it squeezes to fit into 80 chars (even though there's plenty of screen width). See here ...

image

See all the space on the right? I can't seem to get the table to expand any farther right. I've tried the width and expand options, to no effect. I saw where the code is using shutil to get the screen dimensions. Here's the output of that on my screen:

$ python
Python 3.7.5 (default, Nov 24 2019, 09:32:14)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import shutil
>>> shutil.get_terminal_size()
os.terminal_size(columns=158, lines=48)

Your thoughts appreciated.

Collaborator

willmcgugan commented Jan 26, 2020

Strange. The Console class calls shutil.get_terminal_size() under the hood.

How are you constructing Console? If you set width or height it will override the auto-detected terminal size.

What should happen is that if you set expand=True on the Table constructor it will fit the table to the terminal size. If you could post the code you used to construct the Console and Table, I may be able to figure it out.

Author

bwalrond commented Jan 26, 2020

Here's my code ....

Thanks.

Collaborator

willmcgugan commented Jan 26, 2020

Ah. I think that's because you have explicitly set the widths for each column. You'll need at least one column without an explicit width for Rich to expand the table.

The Table class will calculate a minimum width for each column, so you might want to omit the width entirely. You could also set a value for ratio on a column to configure how it expands.

Author

bwalrond commented Jan 26, 2020

Tried it, no luck. Seems like no matter what I do, I can't get the table to be wider than 80 chars.

Collaborator

willmcgugan commented Jan 27, 2020

Running out of suggestions. Obviously works here, but then I'm on OSX. Will try a Linux box soon.

  • Could you print the result of self.console.size and check that matches your terminal size.
  • Run python -m rich.table which should render a table the full width of the terminal.

Just noticed you used os.get_terminal_size and not shutil.get_terminal_size. The later respects COLUMNS and LINES env vars. If your COLUMNS is set to 80, that would explain it.

Author

bwalrond commented Jan 28, 2020

Here ya go ...

$ python
Python 3.7.5 (default, Nov 24 2019, 09:32:14)
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from rich.console import Console
>>> console = Console()
>>> console.size
ConsoleDimensions(width=142, height=38)
>>>

And output of python -m rich.table ...

Look like a module error. I'll try to debug this more when I get some time.

Collaborator

willmcgugan commented Mar 3, 2020

Any chance you can try with the latest version (v0.6.0)? Still haven't managed to reproduce this.

willmcgugan added the Can't reproduce label Mar 9, 2020

willmcgugan closed this as completed Mar 9, 2020

willmcgugan pushed a commit that referenced this issue Jul 15, 2020

Merge pull request #2 from willmcgugan/master

216da4e

willmcgugan pushed a commit that referenced this issue Feb 15, 2021

Merge pull request #2 from willmcgugan/master

ed5834e

willmcgugan pushed a commit that referenced this issue Aug 20, 2021

Fix typos (#2)

5da07fe

willmcgugan added a commit that referenced this issue Aug 20, 2021

Merge pull request #1405 from RojerGS/master

bf7c38b

feluelle commented Feb 22, 2022 • edited

I am seeing the same issue on OSX when I run pytest. It creates a new line char after 78 chars. The total would match then 80 as well.

In my terminal I see a different output longer than 80 chars per line.

EDIT:

Solved it by adding -s flag to pytest.

willmcgugan pushed a commit that referenced this issue Feb 22, 2022

image optimizations (#2)

9a8021c

digitalsignalperson mentioned this issue Jun 1, 2023

[BUG] table autofit doesn't fill window width in Jupyter QtConsole #2983

Closed

2 tasks

salahxgamer commented Aug 15, 2023

I had similar problem where the console intance created didn't have the size of my actual console.

it turned out because i was using cmder, and when running my script from a split console that was smaller, my script opens up in a new full screen console but with old one's dimensions. all in all it was not a fault on rich's end, just putting this out there

kchawla-pi commented Mar 4, 2024

Don't know if still relevant, but I face the same problem as the OP when I use Pycharm's built-in terminal, but not when I use my standalone terminal emulator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Assignees

No one assigned

Projects

None yet

Milestone

No milestone

stephane.bio

Made with Notion, Published on Super - 2026 © Stephane Boghossian

LinkedInInstagramMediumGitHubXBehanceDiscordPinterest
       self.console = Console()

    def outputColumnStats(self):

        table = Table(show_header=True, box=box.ROUNDED, header_style="bold magenta", expand=True)
        table.add_column(header="Column", style="dim", width=9, no_wrap=True)
        table.add_column(header="str",justify="right", width=4, no_wrap=True)
        table.add_column(header="shrt",justify="right", width=5, no_wrap=True)
        table.add_column(header="int",justify="right", width=4, no_wrap=True)
        table.add_column(header="long",justify="right", width=4, no_wrap=True)
        table.add_column(header="flt",justify="right", width=3, no_wrap=True)
        table.add_column(header="date",justify="right", width=4 )
        table.add_column(header="dttm",justify="right", width=4, no_wrap=True)
        table.add_column(header="null",justify="right", width=4, no_wrap=True)


        for k,rows in self.col_stats.items():
            vals = [ "0" for r in range(8) ]
            for r in rows:
                if r[0] == "string":
                    vals[0] = f"{r[1]:,}"
                elif r[0] == "short":
                    vals[1] = f"{r[1]:,}"
                elif r[0] == "integer":
                    vals[2] = f"{r[1]:,}"
                elif r[0] == "long":
                    vals[3] = f"{r[1]:,}"
                elif r[0] == "float":
                    vals[4] = f"{r[1]:,}"
                elif r[0] == "date":
                    vals[5] = f"{r[1]:,}"
                elif r[0] == "datetime":
                    vals[6] = f"{r[1]:,}"
                elif r[0] == "null":
                    vals[7] = f"{r[1]:,}"

            table.add_row(k[:-7], *vals)

        self.console.print(table)

        return
$ python -m rich.table
Traceback (most recent call last):
  File "/home/bill.walrond/.pyenv/versions/3.7.5/lib/python3.7/runpy.py", line 193, in _run_module_as_main
    "__main__", mod_spec)
  File "/home/bill.walrond/.pyenv/versions/3.7.5/lib/python3.7/runpy.py", line 85, in _run_code
    exec(code, run_globals)
  File "/home/bill.walrond/.pyenv/versions/3.7.5/lib/python3.7/site-packages/rich/table.py", line 496, in <module>
    from .markdown import Markdown
  File "/home/bill.walrond/.pyenv/versions/3.7.5/lib/python3.7/site-packages/rich/markdown.py", line 4, in <module>
    from commonmark.blocks import Parser
ModuleNotFoundError: No module named 'commonmark'