Debian Codegraph @

docs/source/progress.rst

raw
1 .. _progress:
2
3 Progress Display
4 ================
5
6 Rich can display continuously updated information regarding the progress of long running tasks / file copies etc. The information displayed is configurable, the default will display a description of the 'task', a progress bar, percentage complete, and estimated time remaining.
7
8 Rich progress display supports multiple tasks, each with a bar and progress information. You can use this to track concurrent tasks where the work is happening in threads or processes.
9
10 To see how the progress display looks, try this from the command line::
11
12 python -m rich.progress
13
14
15 .. note::
16
17 Progress works with Jupyter notebooks, with the caveat that auto-refresh is disabled. You will need to explicitly call :meth:`~rich.progress.Progress.refresh` or set ``refresh=True`` when calling :meth:`~rich.progress.Progress.update`. Or use the :func:`~rich.progress.track` function which does a refresh automatically on each loop.
18
19 Basic Usage
20 -----------
21
22 For basic usage call the :func:`~rich.progress.track` function, which accepts a sequence (such as a list or range object) and an optional description of the job you are working on. The track function will yield values from the sequence and update the progress information on each iteration. Here's an example::
23
24 import time
25 from rich.progress import track
26
27 for i in track(range(20), description="Processing..."):
28 time.sleep(1) # Simulate work being done
29
30 Advanced usage
31 --------------
32
33 If you require multiple tasks in the display, or wish to configure the columns in the progress display, you can work directly with the :class:`~rich.progress.Progress` class. Once you have constructed a Progress object, add task(s) with (:meth:`~rich.progress.Progress.add_task`) and update progress with :meth:`~rich.progress.Progress.update`.
34
35 The Progress class is designed to be used as a *context manager* which will start and stop the progress display automatically.
36
37 Here's a simple example::
38
39 import time
40
41 from rich.progress import Progress
42
43 with Progress() as progress:
44
45 task1 = progress.add_task("[red]Downloading...", total=1000)
46 task2 = progress.add_task("[green]Processing...", total=1000)
47 task3 = progress.add_task("[cyan]Cooking...", total=1000)
48
49 while not progress.finished:
50 progress.update(task1, advance=0.5)
51 progress.update(task2, advance=0.3)
52 progress.update(task3, advance=0.9)
53 time.sleep(0.02)
54
55 The ``total`` value associated with a task is the number of steps that must be completed for the progress to reach 100%. A *step* in this context is whatever makes sense for your application; it could be number of bytes of a file read, or number of images processed, etc.
56
57
58 Starting and stopping
59 ~~~~~~~~~~~~~~~~~~~~~
60
61 The context manager is recommended if you can use it. If you don't use the context manager, be sure to call :meth:`~rich.progress.Progress.start` to start the progress display, and :meth:`~rich.progress.Progress.stop` to stop it.
62
63 Here's an example that doesn't use the context manager::
64
65 import time
66
67 from rich.progress import Progress
68
69 progress = Progress()
70 progress.start()
71 try:
72 task1 = progress.add_task("[red]Downloading...", total=1000)
73 task2 = progress.add_task("[green]Processing...", total=1000)
74 task3 = progress.add_task("[cyan]Cooking...", total=1000)
75
76 while not progress.finished:
77 progress.update(task1, advance=0.5)
78 progress.update(task2, advance=0.3)
79 progress.update(task3, advance=0.9)
80 time.sleep(0.02)
81 finally:
82 progress.stop()
83
84 Note the use of the try / finally, to ensure that ``stop()`` is called.
85
86 Updating tasks
87 ~~~~~~~~~~~~~~
88
89 When you call :meth:`~rich.progress.Progress.add_task` you get back a `Task ID`. Use this ID to call :meth:`~rich.progress.Progress.update` whenever you have completed some work, or any information has changed. Typically you will need to update ``completed`` every time you have completed a step. You can do this by setting ``completed`` directly or by setting ``advance`` which will add to the current ``completed`` value.
90
91 The :meth:`~rich.progress.Progress.update` method collects keyword arguments which are also associated with the task. Use this to supply any additional information you would like to render in the progress display. The additional arguments are stored in ``task.fields`` and may be referenced in :ref:`Column classes<Columns>`.
92
93 Hiding tasks
94 ~~~~~~~~~~~~
95
96 You can show or hide tasks by updating the tasks ``visible`` value. Tasks are visible by default, but you can also add an invisible task by calling :meth:`~rich.progress.Progress.add_task` with ``visible=False``.
97
98
99 Transient progress
100 ~~~~~~~~~~~~~~~~~~
101
102 Normally when you exit the progress context manager (or call :meth:`~rich.progress.Progress.stop`) the last refreshed display remains in the terminal with the cursor on the following line. You can also make the progress display disappear on exit by setting ``transient=True`` on the Progress constructor. Here's an example::
103
104 with Progress(transient=True) as progress:
105 task = progress.add_task("Working", total=100)
106 do_work(task)
107
108 Transient progress displays are useful if you want more minimal output in the terminal when tasks are complete.
109
110 Indeterminate progress
111 ~~~~~~~~~~~~~~~~~~~~~~
112
113 When you add a task it is automatically *started*, which means it will show a progress bar at 0% and the time remaining will be calculated from the current time. This may not work well if there is a long delay before you can start updating progress; you may need to wait for a response from a server or count files in a directory (for example). In these cases you can call :meth:`~rich.progress.Progress.add_task` with ``start=False`` or ``total=None`` which will display a pulsing animation that lets the user know something is working. This is known as an *indeterminate* progress bar. When you have the number of steps you can call :meth:`~rich.progress.Progress.start_task` which will display the progress bar at 0%, then :meth:`~rich.progress.Progress.update` as normal.
114
115 Auto refresh
116 ~~~~~~~~~~~~
117
118 By default, the progress information will refresh 10 times a second. You can set the refresh rate with the ``refresh_per_second`` argument on the :class:`~rich.progress.Progress` constructor. You should set this to something lower than 10 if you know your updates will not be that frequent.
119
120 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. If you disable auto-refresh you will need to call :meth:`~rich.progress.Progress.refresh` manually after updating your task(s).
121
122
123 Expand
124 ~~~~~~
125
126 The progress bar(s) will use only as much of the width of the terminal as required to show the task information. If you set the ``expand`` argument on the Progress constructor, then Rich will stretch the progress display to the full available width.
127
128
129 Columns
130 ~~~~~~~
131
132 You may customize the columns in the progress display with the positional arguments to the :class:`~rich.progress.Progress` constructor. The columns are specified as either a `format string <https://docs.python.org/3/library/string.html#formatspec>`_ or a :class:`~rich.progress.ProgressColumn` object.
133
134 Format strings will be rendered with a single value `"task"` which will be a :class:`~rich.progress.Task` instance. For example ``"{task.description}"`` would display the task description in the column, and ``"{task.completed} of {task.total}"`` would display how many of the total steps have been completed. Additional fields passed via keyword arguments to `~rich.progress.Progress.update` are stored in ``task.fields``. You can add them to a format string with the following syntax: ``"extra info: {task.fields[extra]}"``.
135
136 The default columns are equivalent to the following::
137
138 progress = Progress(
139 TextColumn("[progress.description]{task.description}"),
140 BarColumn(),
141 TaskProgressColumn(),
142 TimeRemainingColumn(),
143 )
144
145 To create a Progress with your own columns in addition to the defaults, use :meth:`~rich.progress.Progress.get_default_columns`::
146
147 progress = Progress(
148 SpinnerColumn(),
149 *Progress.get_default_columns(),
150 TimeElapsedColumn(),
151 )
152
153 The following column objects are available:
154
155 - :class:`~rich.progress.BarColumn` Displays the bar.
156 - :class:`~rich.progress.TextColumn` Displays text.
157 - :class:`~rich.progress.TimeElapsedColumn` Displays the time elapsed.
158 - :class:`~rich.progress.TimeRemainingColumn` Displays the estimated time remaining.
159 - :class:`~rich.progress.MofNCompleteColumn` Displays completion progress as ``"{task.completed}/{task.total}"`` (works best if completed and total are ints).
160 - :class:`~rich.progress.FileSizeColumn` Displays progress as file size (assumes the steps are bytes).
161 - :class:`~rich.progress.TotalFileSizeColumn` Displays total file size (assumes the steps are bytes).
162 - :class:`~rich.progress.DownloadColumn` Displays download progress (assumes the steps are bytes).
163 - :class:`~rich.progress.TransferSpeedColumn` Displays transfer speed (assumes the steps are bytes).
164 - :class:`~rich.progress.SpinnerColumn` Displays a "spinner" animation.
165 - :class:`~rich.progress.RenderableColumn` Displays an arbitrary Rich renderable in the column.
166
167 To implement your own columns, extend the :class:`~rich.progress.ProgressColumn` class and use it as you would the other columns.
168
169
170 Table Columns
171 ~~~~~~~~~~~~~
172
173 Rich builds a :class:`~rich.table.Table` for the tasks in the Progress instance. You can customize how the columns of this *tasks table* are created by specifying the ``table_column`` argument in the Column constructor, which should be a :class:`~rich.table.Column` instance.
174
175 The following example demonstrates a progress bar where the description takes one third of the width of the terminal, and the bar takes up the remaining two thirds::
176
177 from time import sleep
178
179 from rich.table import Column
180 from rich.progress import Progress, BarColumn, TextColumn
181
182 text_column = TextColumn("{task.description}", table_column=Column(ratio=1))
183 bar_column = BarColumn(bar_width=None, table_column=Column(ratio=2))
184 progress = Progress(text_column, bar_column, expand=True)
185
186 with progress:
187 for n in progress.track(range(100)):
188 progress.print(n)
189 sleep(0.1)
190
191
192 Print / log
193 ~~~~~~~~~~~
194
195 The Progress class will create an internal Console object which you can access via ``progress.console``. If you print or log to this console, the output will be displayed *above* the progress display. Here's an example::
196
197 with Progress() as progress:
198 task = progress.add_task("twiddling thumbs", total=10)
199 for job in range(10):
200 progress.console.print(f"Working on job #{job}")
201 run_job(job)
202 progress.advance(task)
203
204 If you have another Console object you want to use, pass it in to the :class:`~rich.progress.Progress` constructor. Here's an example::
205
206 from my_project import my_console
207
208 with Progress(console=my_console) as progress:
209 my_console.print("[bold blue]Starting work!")
210 do_work(progress)
211
212
213 Redirecting stdout / stderr
214 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
215
216 To avoid breaking the progress display visuals, Rich will redirect ``stdout`` and ``stderr`` so that you can use the built-in ``print`` statement. This feature is enabled by default, but you can disable by setting ``redirect_stdout`` or ``redirect_stderr`` to ``False``
217
218
219 Customizing
220 ~~~~~~~~~~~
221
222 If the :class:`~rich.progress.Progress` class doesn't offer exactly what you need in terms of a progress display, you can override the :class:`~rich.progress.Progress.get_renderables` method. For example, the following class will render a :class:`~rich.panel.Panel` around the progress display::
223
224 from rich.panel import Panel
225 from rich.progress import Progress
226
227 class MyProgress(Progress):
228 def get_renderables(self):
229 yield Panel(self.make_tasks_table(self.tasks))
230
231 Reading from a file
232 ~~~~~~~~~~~~~~~~~~~
233
234 Rich provides an easy way to generate a progress bar while reading a file. If you call :func:`~rich.progress.open` it will return a context manager which displays a progress bar while you read. This is particularly useful when you can't easily modify the code that does the reading.
235
236 The following example demonstrates how we might show progress when reading a JSON file::
237
238 import json
239 import rich.progress
240
241 with rich.progress.open("data.json", "rb") as file:
242 data = json.load(file)
243 print(data)
244
245 If you already have a file object, you can call :func:`~rich.progress.wrap_file` which returns a context manager that wraps your file so that it displays a progress bar. If you use this function you will need to set the number of bytes or characters you expect to read.
246
247 Here's an example that reads a url from the internet::
248
249 from time import sleep
250 from urllib.request import urlopen
251
252 from rich.progress import wrap_file
253
254 response = urlopen("https://www.textualize.io")
255 size = int(response.headers["Content-Length"])
256
257 with wrap_file(response, size) as file:
258 for line in file:
259 print(line.decode("utf-8"), end="")
260 sleep(0.1)
261
262
263 If you expect to be reading from multiple files, you can use :meth:`~rich.progress.Progress.open` or :meth:`~rich.progress.Progress.wrap_file` to add a file progress to an existing Progress instance.
264
265 See `cp_progress.py <https://github.com/willmcgugan/rich/blob/master/examples/cp_progress.py>`_ for a minimal clone of the ``cp`` command which shows a progress bar as the file is copied.
266
267
268 Nesting Progress bars
269 ---------------------
270
271 If you create a new progress bar within the context of an existing progress bar (with the context manager or `track` function), then Rich will display the inner progress bar(s) under the initial bar.
272
273 Here's an example that nests progress bars::
274
275 from rich.progress import track
276 from time import sleep
277
278
279 for count in track(range(10)):
280 for letter in track("ABCDEF", transient=True):
281 print(f"Stage {count}{letter}")
282 sleep(0.1)
283 sleep(0.1)
284
285 The inner loop creates a new progress bar below the first, but both can update.
286
287 Note that if you nest progress bars like this, then the nested bars will updating according to the `refresh_per_second` attribute of the outer bar.
288
289
290 Multiple Progress
291 -----------------
292
293 You can't have different columns per task with a single Progress instance. However, you can have as many Progress instances as you like in a :ref:`live`. See `live_progress.py <https://github.com/willmcgugan/rich/blob/master/examples/live_progress.py>`_ and `dynamic_progress.py <https://github.com/willmcgugan/rich/blob/master/examples/dynamic_progress.py>`_ for examples of using multiple Progress instances.
294
295 Example
296 -------
297
298 See `downloader.py <https://github.com/willmcgugan/rich/blob/master/examples/downloader.py>`_ for a realistic application of a progress display. This script can download multiple concurrent files with a progress bar, transfer speed and file size.