Debian Codegraph @

docs/source/live.rst

raw
1 .. _live:
2
3 Live Display
4 ============
5
6 Progress bars and status indicators use a *live* display to animate parts of the terminal. You can build custom live displays with the :class:`~rich.live.Live` class.
7
8 For a demonstration of a live display, run the following command::
9
10 python -m rich.live
11
12 .. note::
13
14 If you see ellipsis "...", this indicates that the terminal is not tall enough to show the full table.
15
16 Basic usage
17 ~~~~~~~~~~~
18
19 To create a live display, construct a :class:`~rich.live.Live` object with a renderable and use it as a context manager. The live display will persist for the duration of the context. You can update the renderable to update the display::
20
21
22 import time
23
24 from rich.live import Live
25 from rich.table import Table
26
27 table = Table()
28 table.add_column("Row ID")
29 table.add_column("Description")
30 table.add_column("Level")
31
32 with Live(table, refresh_per_second=4): # update 4 times a second to feel fluid
33 for row in range(12):
34 time.sleep(0.4) # arbitrary delay
35 # update the renderable internally
36 table.add_row(f"{row}", f"description {row}", "[red]ERROR")
37
38
39 Updating the renderable
40 ~~~~~~~~~~~~~~~~~~~~~~~
41
42 You can also change the renderable on-the-fly by calling the :meth:`~rich.live.Live.update` method. This may be useful if the information you wish to display is too dynamic to generate by updating a single renderable. Here is an example::
43
44 import random
45 import time
46
47 from rich.live import Live
48 from rich.table import Table
49
50
51 def generate_table() -> Table:
52 """Make a new table."""
53 table = Table()
54 table.add_column("ID")
55 table.add_column("Value")
56 table.add_column("Status")
57
58 for row in range(random.randint(2, 6)):
59 value = random.random() * 100
60 table.add_row(
61 f"{row}", f"{value:3.2f}", "[red]ERROR" if value < 50 else "[green]SUCCESS"
62 )
63 return table
64
65
66 with Live(generate_table(), refresh_per_second=4) as live:
67 for _ in range(40):
68 time.sleep(0.4)
69 live.update(generate_table())
70
71
72 Alternate screen
73 ~~~~~~~~~~~~~~~~
74
75 You can opt to show a Live display in the "alternate screen" by setting ``screen=True`` on the constructor. This will allow your live display to go full screen and restore the command prompt on exit.
76
77 You can use this feature in combination with :ref:`Layout` to display sophisticated terminal "applications".
78
79 Transient display
80 ~~~~~~~~~~~~~~~~~
81
82 Normally when you exit live context manager (or call :meth:`~rich.live.Live.stop`) the last refreshed item remains in the terminal with the cursor on the following line.
83 You can also make the live display disappear on exit by setting ``transient=True`` on the Live constructor.
84
85 Auto refresh
86 ~~~~~~~~~~~~
87
88 By default, the live display will refresh 4 times a second. You can set the refresh rate with the ``refresh_per_second`` argument on the :class:`~rich.live.Live` constructor.
89 You should set this to something lower than 4 if you know your updates will not be that frequent or higher for a smoother feeling.
90
91 You might want to disable auto-refresh entirely if your updates are not very frequent, which you can do by setting ``auto_refresh=False`` on the constructor.
92 If you disable auto-refresh you will need to call :meth:`~rich.live.Live.refresh` manually or :meth:`~rich.live.Live.update` with ``refresh=True``.
93
94 Vertical overflow
95 ~~~~~~~~~~~~~~~~~
96
97 By default, the live display will display ellipsis if the renderable is too large for the terminal. You can adjust this by setting the
98 ``vertical_overflow`` argument on the :class:`~rich.live.Live` constructor.
99
100 - "crop" Show renderable up to the terminal height. The rest is hidden.
101 - "ellipsis" Similar to crop except last line of the terminal is replaced with "...". This is the default behavior.
102 - "visible" Will allow the whole renderable to be shown. Note that the display cannot be properly cleared in this mode.
103
104 .. note::
105
106 Once the live display stops on a non-transient renderable, the last frame will render as **visible** since it doesn't have to be cleared.
107
108
109 Print / log
110 ~~~~~~~~~~~
111
112 The Live class will create an internal Console object which you can access via ``live.console``. If you print or log to this console, the output will be displayed *above* the live display. Here's an example::
113
114 import time
115
116 from rich.live import Live
117 from rich.table import Table
118
119 table = Table()
120 table.add_column("Row ID")
121 table.add_column("Description")
122 table.add_column("Level")
123
124 with Live(table, refresh_per_second=4) as live: # update 4 times a second to feel fluid
125 for row in range(12):
126 live.console.print(f"Working on row #{row}")
127 time.sleep(0.4)
128 table.add_row(f"{row}", f"description {row}", "[red]ERROR")
129
130
131 If you have another Console object you want to use, pass it in to the :class:`~rich.live.Live` constructor. Here's an example::
132
133 from my_project import my_console
134
135 with Live(console=my_console) as live:
136 my_console.print("[bold blue]Starting work!")
137 ...
138
139 .. note::
140
141 If you are passing in a file console, the live display only show the last item once the live context is left.
142
143 Redirecting stdout / stderr
144 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
145
146 To avoid breaking the live display visuals, Rich will redirect ``stdout`` and ``stderr`` so that you can use the builtin ``print`` statement.
147 This feature is enabled by default, but you can disable by setting ``redirect_stdout`` or ``redirect_stderr`` to ``False``.
148
149 Nesting Lives
150 -------------
151
152 If you create a Live instance within the context of an existing Live instance, then the content of the inner Live will be displayed below the outer Live.
153
154 Prior to version 14.0.0 this would have resulted in a :class:`~rich.errors.LiveError` exception.
155
156
157 Examples
158 --------
159
160 See `table_movie.py <https://github.com/willmcgugan/rich/blob/master/examples/table_movie.py>`_ and
161 `top_lite_simulator.py <https://github.com/willmcgugan/rich/blob/master/examples/top_lite_simulator.py>`_
162 for deeper examples of live displaying.