5from abc
import ABC, abstractmethod
6from collections
import deque
7from dataclasses
import dataclass, field
8from datetime
import timedelta
9from io
import RawIOBase, UnsupportedOperation
12from operator
import length_hint
13from os
import PathLike, stat
14from threading
import Event, RLock, Thread
15from types
import TracebackType
38 from typing
import Literal
42from .
import filesize, get_console
43from .console
import Console, Group, JustifyMethod, RenderableType
44from .highlighter
import Highlighter
45from .jupyter
import JupyterMixin
47from .progress_bar
import ProgressBar
48from .spinner
import Spinner
49from .style
import StyleType
50from .table
import Column, Table
51from .text
import Text, TextType
53TaskID = NewType(
"TaskID", int)
55ProgressType = TypeVar(
"ProgressType")
57GetTimeCallable = Callable[[], float]
64 """A thread to periodically update progress."""
66 def __init__(self, progress:
"Progress", task_id:
"TaskID", update_period: float):
75 def run(self) -> None:
81 while not wait(update_period):
83 if last_completed != completed:
84 advance(task_id, completed - last_completed)
85 last_completed = completed
95 exc_type: Optional[Type[BaseException]],
96 exc_val: Optional[BaseException],
97 exc_tb: Optional[TracebackType],
104 sequence: Union[Sequence[ProgressType], Iterable[ProgressType]],
105 description: str =
"Working...",
106 total: Optional[float] =
None,
107 auto_refresh: bool =
True,
108 console: Optional[Console] =
None,
109 transient: bool =
False,
110 get_time: Optional[Callable[[], float]] =
None,
111 refresh_per_second: float = 10,
112 style: StyleType =
"bar.back",
113 complete_style: StyleType =
"bar.complete",
114 finished_style: StyleType =
"bar.finished",
115 pulse_style: StyleType =
"bar.pulse",
116 update_period: float = 0.1,
117 disable: bool =
False,
118 show_speed: bool =
True,
119) -> Iterable[ProgressType]:
120 """Track progress by iterating over a sequence.
123 sequence (Iterable[ProgressType]): A sequence (must support "len") you wish to iterate over.
124 description (str, optional): Description of task show next to progress bar. Defaults to "Working".
125 total: (float, optional): Total number of steps. Default is len(sequence).
126 auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
127 transient: (bool, optional): Clear the progress on exit. Defaults to False.
128 console (Console, optional): Console to write to. Default creates internal Console instance.
129 refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
130 style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
131 complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
132 finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
133 pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
134 update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.
135 disable (bool, optional): Disable display of progress.
136 show_speed (bool, optional): Show speed if total isn't known. Defaults to True.
138 Iterable[ProgressType]: An iterable of the values in the sequence.
142 columns: List[
"ProgressColumn"] = (
143 [
TextColumn(
"[progress.description]{task.description}")]
if description
else []
149 complete_style=complete_style,
150 finished_style=finished_style,
151 pulse_style=pulse_style,
159 auto_refresh=auto_refresh,
163 refresh_per_second=refresh_per_second
or 10,
169 sequence, total=total, description=description, update_period=update_period
174 """A reader that tracks progress while it's being read from."""
179 progress:
"Progress",
181 close_handle: bool =
True,
195 exc_type: Optional[Type[BaseException]],
196 exc_val: Optional[BaseException],
197 exc_tb: Optional[TracebackType],
224 def name(self) -> str:
236 def read(self, size: int = -1) -> bytes:
241 def readinto(self, b: Union[bytearray, memoryview, mmap]):
261 def seek(self, offset: int, whence: int = 0) -> int:
270 raise UnsupportedOperation(
"write")
274 """A utility class to handle a context for both a reader and a progress."""
276 def __init__(self, progress:
"Progress", reader: _I) ->
None:
278 self.reader: _I = reader
286 exc_type: Optional[Type[BaseException]],
287 exc_val: Optional[BaseException],
288 exc_tb: Optional[TracebackType],
291 self.reader.
__exit__(exc_type, exc_val, exc_tb)
298 description: str =
"Reading...",
299 auto_refresh: bool =
True,
300 console: Optional[Console] =
None,
301 transient: bool =
False,
302 get_time: Optional[Callable[[], float]] =
None,
303 refresh_per_second: float = 10,
304 style: StyleType =
"bar.back",
305 complete_style: StyleType =
"bar.complete",
306 finished_style: StyleType =
"bar.finished",
307 pulse_style: StyleType =
"bar.pulse",
308 disable: bool =
False,
309) -> ContextManager[BinaryIO]:
310 """Read bytes from a file while tracking progress.
313 file (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.
314 total (int): Total number of bytes to read.
315 description (str, optional): Description of task show next to progress bar. Defaults to "Reading".
316 auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
317 transient: (bool, optional): Clear the progress on exit. Defaults to False.
318 console (Console, optional): Console to write to. Default creates internal Console instance.
319 refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
320 style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
321 complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
322 finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
323 pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
324 disable (bool, optional): Disable display of progress.
326 ContextManager[BinaryIO]: A context manager yielding a progress reader.
330 columns: List[
"ProgressColumn"] = (
331 [
TextColumn(
"[progress.description]{task.description}")]
if description
else []
337 complete_style=complete_style,
338 finished_style=finished_style,
339 pulse_style=pulse_style,
347 auto_refresh=auto_refresh,
351 refresh_per_second=refresh_per_second
or 10,
361 file: Union[str,
"PathLike[str]", bytes],
362 mode: Union[Literal[
"rt"], Literal[
"r"]],
364 encoding: Optional[str] =
None,
365 errors: Optional[str] =
None,
366 newline: Optional[str] =
None,
368 total: Optional[int] =
None,
369 description: str =
"Reading...",
370 auto_refresh: bool =
True,
371 console: Optional[Console] =
None,
372 transient: bool =
False,
373 get_time: Optional[Callable[[], float]] =
None,
374 refresh_per_second: float = 10,
375 style: StyleType =
"bar.back",
376 complete_style: StyleType =
"bar.complete",
377 finished_style: StyleType =
"bar.finished",
378 pulse_style: StyleType =
"bar.pulse",
379 disable: bool =
False,
380) -> ContextManager[TextIO]:
386 file: Union[str,
"PathLike[str]", bytes],
389 encoding: Optional[str] =
None,
390 errors: Optional[str] =
None,
391 newline: Optional[str] =
None,
393 total: Optional[int] =
None,
394 description: str =
"Reading...",
395 auto_refresh: bool =
True,
396 console: Optional[Console] =
None,
397 transient: bool =
False,
398 get_time: Optional[Callable[[], float]] =
None,
399 refresh_per_second: float = 10,
400 style: StyleType =
"bar.back",
401 complete_style: StyleType =
"bar.complete",
402 finished_style: StyleType =
"bar.finished",
403 pulse_style: StyleType =
"bar.pulse",
404 disable: bool =
False,
405) -> ContextManager[BinaryIO]:
410 file: Union[str,
"PathLike[str]", bytes],
411 mode: Union[Literal[
"rb"], Literal[
"rt"], Literal[
"r"]] =
"r",
413 encoding: Optional[str] =
None,
414 errors: Optional[str] =
None,
415 newline: Optional[str] =
None,
417 total: Optional[int] =
None,
418 description: str =
"Reading...",
419 auto_refresh: bool =
True,
420 console: Optional[Console] =
None,
421 transient: bool =
False,
422 get_time: Optional[Callable[[], float]] =
None,
423 refresh_per_second: float = 10,
424 style: StyleType =
"bar.back",
425 complete_style: StyleType =
"bar.complete",
426 finished_style: StyleType =
"bar.finished",
427 pulse_style: StyleType =
"bar.pulse",
428 disable: bool =
False,
429) -> Union[ContextManager[BinaryIO], ContextManager[TextIO]]:
430 """Read bytes from a file while tracking progress.
433 path (Union[str, PathLike[str], BinaryIO]): The path to the file to read, or a file-like object in binary mode.
434 mode (str): The mode to use to open the file. Only supports "r", "rb" or "rt".
435 buffering (int): The buffering strategy to use, see :func:`io.open`.
436 encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`.
437 errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`.
438 newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open`
439 total: (int, optional): Total number of bytes to read. Must be provided if reading from a file handle. Default for a path is os.stat(file).st_size.
440 description (str, optional): Description of task show next to progress bar. Defaults to "Reading".
441 auto_refresh (bool, optional): Automatic refresh, disable to force a refresh after each iteration. Default is True.
442 transient: (bool, optional): Clear the progress on exit. Defaults to False.
443 console (Console, optional): Console to write to. Default creates internal Console instance.
444 refresh_per_second (float): Number of times per second to refresh the progress information. Defaults to 10.
445 style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
446 complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
447 finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
448 pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
449 disable (bool, optional): Disable display of progress.
450 encoding (str, optional): The encoding to use when reading in text mode.
453 ContextManager[BinaryIO]: A context manager yielding a progress reader.
457 columns: List[
"ProgressColumn"] = (
458 [
TextColumn(
"[progress.description]{task.description}")]
if description
else []
464 complete_style=complete_style,
465 finished_style=finished_style,
466 pulse_style=pulse_style,
474 auto_refresh=auto_refresh,
478 refresh_per_second=refresh_per_second
or 10,
490 description=description,
496 """Base class for a widget to use in progress display."""
498 max_refresh: Optional[float] =
None
500 def __init__(self, table_column: Optional[Column] =
None) ->
None:
502 self._renderable_cache: Dict[TaskID, Tuple[float, RenderableType]] = {}
503 self._update_time: Optional[float] =
None
506 """Get a table column, used to build tasks table."""
509 def __call__(self, task:
"Task") -> RenderableType:
510 """Called by the Progress object to return a renderable for the given task.
513 task (Task): An object containing information regarding the task.
516 RenderableType: Anything renderable (including str).
521 timestamp, renderable = self._renderable_cache[
task.id]
528 renderable = self.
render(task)
529 self._renderable_cache[
task.id] = (current_time, renderable)
533 def render(self, task:
"Task") -> RenderableType:
534 """Should return a renderable object."""
538 """A column to insert an arbitrary column.
541 renderable (RenderableType, optional): Any renderable. Defaults to empty string.
545 self, renderable: RenderableType =
"", *, table_column: Optional[Column] =
None
550 def render(self, task:
"Task") -> RenderableType:
555 """A column with a 'spinner' animation.
558 spinner_name (str, optional): Name of spinner animation. Defaults to "dots".
559 style (StyleType, optional): Style of spinner. Defaults to "progress.spinner".
560 speed (float, optional): Speed factor of spinner. Defaults to 1.0.
561 finished_text (TextType, optional): Text used when task is finished. Defaults to " ".
566 spinner_name: str =
"dots",
567 style: Optional[StyleType] =
"progress.spinner",
569 finished_text: TextType =
" ",
570 table_column: Optional[Column] =
None,
583 spinner_style: Optional[StyleType] =
"progress.spinner",
586 """Set a new spinner.
589 spinner_name (str): Spinner name, see python -m rich.spinner.
590 spinner_style (Optional[StyleType], optional): Spinner style. Defaults to "progress.spinner".
591 speed (float, optional): Speed factor of spinner. Defaults to 1.0.
593 self.
spinner =
Spinner(spinner_name, style=spinner_style, speed=speed)
595 def render(self, task:
"Task") -> RenderableType:
605 """A column containing text."""
610 style: StyleType =
"none",
611 justify: JustifyMethod =
"left",
613 highlighter: Optional[Highlighter] =
None,
614 table_column: Optional[Column] =
None,
617 self.justify: JustifyMethod = justify
623 def render(self, task:
"Task") -> Text:
628 text =
Text(_text, style=self.
style, justify=self.justify)
635 """Renders a visual progress bar.
638 bar_width (Optional[int], optional): Width of bar or None for full width. Defaults to 40.
639 style (StyleType, optional): Style for the bar background. Defaults to "bar.back".
640 complete_style (StyleType, optional): Style for the completed bar. Defaults to "bar.complete".
641 finished_style (StyleType, optional): Style for a finished bar. Defaults to "bar.finished".
642 pulse_style (StyleType, optional): Style for pulsing bars. Defaults to "bar.pulse".
647 bar_width: Optional[int] = 40,
648 style: StyleType =
"bar.back",
649 complete_style: StyleType =
"bar.complete",
650 finished_style: StyleType =
"bar.finished",
651 pulse_style: StyleType =
"bar.pulse",
652 table_column: Optional[Column] =
None,
661 def render(self, task:
"Task") -> ProgressBar:
662 """Gets a progress bar widget for a task."""
677 """Renders time elapsed."""
679 def render(self, task:
"Task") -> Text:
680 """Show time elapsed."""
683 return Text(
"-:--:--", style=
"progress.elapsed")
684 delta = timedelta(seconds=int(elapsed))
685 return Text(str(delta), style=
"progress.elapsed")
689 """Show task progress as a percentage.
692 text_format (str, optional): Format for percentage display. Defaults to "[progress.percentage]{task.percentage:>3.0f}%".
693 text_format_no_percentage (str, optional): Format if percentage is unknown. Defaults to "".
694 style (StyleType, optional): Style of output. Defaults to "none".
695 justify (JustifyMethod, optional): Text justification. Defaults to "left".
696 markup (bool, optional): Enable markup. Defaults to True.
697 highlighter (Optional[Highlighter], optional): Highlighter to apply to output. Defaults to None.
698 table_column (Optional[Column], optional): Table Column to use. Defaults to None.
699 show_speed (bool, optional): Show speed if total is unknown. Defaults to False.
704 text_format: str =
"[progress.percentage]{task.percentage:>3.0f}%",
705 text_format_no_percentage: str =
"",
706 style: StyleType =
"none",
707 justify: JustifyMethod =
"left",
709 highlighter: Optional[Highlighter] =
None,
710 table_column: Optional[Column] =
None,
711 show_speed: bool =
False,
717 text_format=text_format,
721 highlighter=highlighter,
722 table_column=table_column,
727 """Render the speed in iterations per second.
730 task (Task): A Task object.
733 Text: Text object containing the task speed.
736 return Text(
"", style=
"progress.percentage")
739 [
"",
"×10³",
"×10⁶",
"×10⁹",
"×10¹²"],
742 data_speed = speed / unit
743 return Text(f
"{data_speed:.1f}{suffix} it/s", style=
"progress.percentage")
745 def render(self, task:
"Task") -> Text:
755 text =
Text(_text, style=self.
style, justify=self.justify)
762 """Renders estimated time remaining.
765 compact (bool, optional): Render MM:SS when time remaining is less than an hour. Defaults to False.
766 elapsed_when_finished (bool, optional): Render time elapsed when the task is finished. Defaults to False.
774 compact: bool =
False,
775 elapsed_when_finished: bool =
False,
776 table_column: Optional[Column] =
None,
782 def render(self, task:
"Task") -> Text:
783 """Show time remaining."""
786 style =
"progress.elapsed"
789 style =
"progress.remaining"
792 return Text(
"", style=style)
794 if task_time
is None:
795 return Text(
"--:--" if self.
compact else "-:--:--", style=style)
798 minutes, seconds =
divmod(int(task_time), 60)
799 hours, minutes =
divmod(minutes, 60)
802 formatted = f
"{minutes:02d}:{seconds:02d}"
804 formatted = f
"{hours:d}:{minutes:02d}:{seconds:02d}"
806 return Text(formatted, style=style)
810 """Renders completed filesize."""
812 def render(self, task:
"Task") -> Text:
813 """Show data completed."""
815 return Text(data_size, style=
"progress.filesize")
819 """Renders total filesize."""
821 def render(self, task:
"Task") -> Text:
822 """Show data completed."""
824 return Text(data_size, style=
"progress.filesize.total")
828 """Renders completed count/total, e.g. ' 10/1000'.
830 Best for bounded tasks with int quantities.
832 Space pads the completed count so that progress length does not change as task progresses
836 separator (str, optional): Text to separate completed and total values. Defaults to "/".
839 def __init__(self, separator: str =
"/", table_column: Optional[Column] =
None):
843 def render(self, task:
"Task") -> Text:
844 """Show completed/total."""
847 total_width =
len(str(total))
849 f
"{completed:{total_width}d}{self.separator}{total}",
850 style=
"progress.download",
855 """Renders file size downloaded and total, e.g. '0.5/2.3 GB'.
858 binary_units (bool, optional): Use binary units, KiB, MiB etc. Defaults to False.
862 self, binary_units: bool =
False, table_column: Optional[Column] =
None
867 def render(self, task:
"Task") -> Text:
868 """Calculate common unit for completed and total."""
871 unit_and_suffix_calculation_base = (
876 unit_and_suffix_calculation_base,
877 [
"bytes",
"KiB",
"MiB",
"GiB",
"TiB",
"PiB",
"EiB",
"ZiB",
"YiB"],
882 unit_and_suffix_calculation_base,
883 [
"bytes",
"kB",
"MB",
"GB",
"TB",
"PB",
"EB",
"ZB",
"YB"],
886 precision = 0
if unit == 1
else 1
888 completed_ratio = completed / unit
889 completed_str = f
"{completed_ratio:,.{precision}f}"
893 total_ratio = total / unit
894 total_str = f
"{total_ratio:,.{precision}f}"
898 download_status = f
"{completed_str}/{total_str} {suffix}"
899 download_text =
Text(download_status, style=
"progress.download")
904 """Renders human readable transfer speed."""
906 def render(self, task:
"Task") -> Text:
907 """Show data transfer speed."""
910 return Text(
"?", style=
"progress.data.speed")
912 return Text(f
"{data_speed}/s", style=
"progress.data.speed")
916 """Sample of progress for a given time."""
919 """Timestamp of sample."""
921 """Number of steps completed."""
926 """Information regarding a progress task.
928 This object should be considered read-only outside of the :class:`~Progress` class.
933 """Task ID associated with this task (used in Progress methods)."""
936 """str: Description of the task."""
938 total: Optional[float]
939 """Optional[float]: Total number of steps in this task."""
942 """float: Number of steps completed"""
944 _get_time: GetTimeCallable
945 """Callable to get the current time."""
947 finished_time: Optional[float] =
None
948 """float: Time task was finished."""
951 """bool: Indicates if this task is visible in the progress display."""
953 fields: Dict[str, Any] = field(default_factory=dict)
954 """dict: Arbitrary fields passed in via Progress.update."""
956 start_time: Optional[float] = field(default=
None, init=
False, repr=
False)
957 """Optional[float]: Time this task was started, or None if not started."""
959 stop_time: Optional[float] = field(default=
None, init=
False, repr=
False)
960 """Optional[float]: Time this task was stopped, or None if not stopped."""
962 finished_speed: Optional[float] =
None
963 """Optional[float]: The last speed for a finished task."""
965 _progress: Deque[ProgressSample] = field(
966 default_factory=
lambda: deque(maxlen=1000), init=
False, repr=
False
969 _lock: RLock = field(repr=
False, default_factory=RLock)
973 """float: Get the current time, in seconds."""
978 """bool: Check if the task as started."""
983 """Optional[float]: Get the number of steps remaining, if a non-None total was set."""
984 if self.
total is None:
990 """Optional[float]: Time elapsed since task was started, or ``None`` if the task hasn't started."""
999 """Check if the task has finished."""
1004 """float: Get progress of task as a percentage. If a None total was set, returns 0"""
1008 completed = min(100.0, max(0.0, completed))
1013 """Optional[float]: Get the estimated speed in steps per second."""
1020 total_time = progress[-1].timestamp - progress[0].timestamp
1023 iter_progress = iter(progress)
1026 speed = total_completed / total_time
1031 """Optional[float]: Get estimated time to completion, or ``None`` if no data."""
1038 if remaining
is None:
1040 estimate = ceil(remaining / speed)
1044 """Reset progress."""
1051 """Renders an auto-updating progress bar(s).
1054 console (Console, optional): Optional Console instance. Default will an internal Console instance writing to stdout.
1055 auto_refresh (bool, optional): Enable auto refresh. If disabled, you will need to call `refresh()`.
1056 refresh_per_second (Optional[float], optional): Number of times per second to refresh the progress information or None to use default (10). Defaults to None.
1057 speed_estimate_period: (float, optional): Period (in seconds) used to calculate the speed estimate. Defaults to 30.
1058 transient: (bool, optional): Clear the progress on exit. Defaults to False.
1059 redirect_stdout: (bool, optional): Enable redirection of stdout, so ``print`` may be used. Defaults to True.
1060 redirect_stderr: (bool, optional): Enable redirection of stderr. Defaults to True.
1061 get_time: (Callable, optional): A callable that gets the current time, or None to use Console.get_time. Defaults to None.
1062 disable (bool, optional): Disable progress display. Defaults to False
1063 expand (bool, optional): Expand tasks table to fit width. Defaults to False.
1068 *columns: Union[str, ProgressColumn],
1069 console: Optional[Console] =
None,
1070 auto_refresh: bool =
True,
1071 refresh_per_second: float = 10,
1072 speed_estimate_period: float = 30.0,
1073 transient: bool =
False,
1074 redirect_stdout: bool =
True,
1075 redirect_stderr: bool =
True,
1076 get_time: Optional[GetTimeCallable] =
None,
1077 disable: bool =
False,
1078 expand: bool =
False,
1080 assert refresh_per_second > 0,
"refresh_per_second must be > 0"
1087 self._tasks: Dict[TaskID, Task] = {}
1090 console=console
or get_console(),
1091 auto_refresh=auto_refresh,
1092 refresh_per_second=refresh_per_second,
1093 transient=transient,
1094 redirect_stdout=redirect_stdout,
1095 redirect_stderr=redirect_stderr,
1104 """Get the default columns used for a new Progress instance:
1105 - a text column for the description (TextColumn)
1106 - the bar itself (BarColumn)
1107 - a text column showing completion percentage (TextColumn)
1108 - an estimated-time-remaining column (TimeRemainingColumn)
1109 If the Progress instance is created without passing a columns argument,
1110 the default columns defined here will be used.
1112 You can also create a Progress instance using custom columns before
1113 and/or after the defaults, as in this example:
1115 progress = Progress(
1117 *Progress.default_columns(),
1119 TimeElapsedColumn(),
1122 This code shows the creation of a Progress display, containing
1123 a spinner to the left, the default columns, and a labeled elapsed
1127 TextColumn(
"[progress.description]{task.description}"),
1135 return self.
live.console
1139 """Get a list of Task instances."""
1141 return list(self._tasks.values())
1145 """A list of task IDs."""
1147 return list(self._tasks.keys())
1151 """Check if all tasks have been completed."""
1158 """Start the progress display."""
1163 """Stop the progress display."""
1165 if not self.
console.is_interactive:
1174 exc_type: Optional[Type[BaseException]],
1175 exc_val: Optional[BaseException],
1176 exc_tb: Optional[TracebackType],
1182 sequence: Union[Iterable[ProgressType], Sequence[ProgressType]],
1183 total: Optional[float] =
None,
1184 task_id: Optional[TaskID] =
None,
1185 description: str =
"Working...",
1186 update_period: float = 0.1,
1187 ) -> Iterable[ProgressType]:
1188 """Track progress by iterating over a sequence.
1191 sequence (Sequence[ProgressType]): A sequence of values you want to iterate over and track progress.
1192 total: (float, optional): Total number of steps. Default is len(sequence).
1193 task_id: (TaskID): Task to track. Default is new task.
1194 description: (str, optional): Description of task, if new task is created.
1195 update_period (float, optional): Minimum time (in seconds) between calls to update(). Defaults to 0.1.
1198 Iterable[ProgressType]: An iterable of values taken from the provided sequence.
1201 total = float(length_hint(sequence))
or None
1204 task_id = self.
add_task(description, total=total)
1206 self.
update(task_id, total=total)
1208 if self.
live.auto_refresh:
1209 with _TrackThread(self, task_id, update_period)
as track_thread:
1210 for value
in sequence:
1216 for value
in sequence:
1224 total: Optional[int] =
None,
1226 task_id: Optional[TaskID] =
None,
1227 description: str =
"Reading...",
1229 """Track progress file reading from a binary file.
1232 file (BinaryIO): A file-like object opened in binary mode.
1233 total (int, optional): Total number of bytes to read. This must be provided unless a task with a total is also given.
1234 task_id (TaskID): Task to track. Default is new task.
1235 description (str, optional): Description of task, if new task is created.
1238 BinaryIO: A readable file-like object in binary mode.
1241 ValueError: When no total value can be extracted from the arguments or the task.
1244 total_bytes: Optional[float] =
None
1245 if total
is not None:
1247 elif task_id
is not None:
1249 total_bytes = self._tasks[task_id].total
1250 if total_bytes
is None:
1252 f
"unable to get the total number of bytes, please specify 'total'"
1257 task_id = self.
add_task(description, total=total_bytes)
1259 self.
update(task_id, total=total_bytes)
1261 return _Reader(file, self, task_id, close_handle=
False)
1266 file: Union[str,
"PathLike[str]", bytes],
1267 mode: Literal[
"rb"],
1268 buffering: int = -1,
1269 encoding: Optional[str] =
None,
1270 errors: Optional[str] =
None,
1271 newline: Optional[str] =
None,
1273 total: Optional[int] =
None,
1274 task_id: Optional[TaskID] =
None,
1275 description: str =
"Reading...",
1282 file: Union[str,
"PathLike[str]", bytes],
1283 mode: Union[Literal[
"r"], Literal[
"rt"]],
1284 buffering: int = -1,
1285 encoding: Optional[str] =
None,
1286 errors: Optional[str] =
None,
1287 newline: Optional[str] =
None,
1289 total: Optional[int] =
None,
1290 task_id: Optional[TaskID] =
None,
1291 description: str =
"Reading...",
1297 file: Union[str,
"PathLike[str]", bytes],
1298 mode: Union[Literal[
"rb"], Literal[
"rt"], Literal[
"r"]] =
"r",
1299 buffering: int = -1,
1300 encoding: Optional[str] =
None,
1301 errors: Optional[str] =
None,
1302 newline: Optional[str] =
None,
1304 total: Optional[int] =
None,
1305 task_id: Optional[TaskID] =
None,
1306 description: str =
"Reading...",
1307 ) -> Union[BinaryIO, TextIO]:
1308 """Track progress while reading from a binary file.
1311 path (Union[str, PathLike[str]]): The path to the file to read.
1312 mode (str): The mode to use to open the file. Only supports "r", "rb" or "rt".
1313 buffering (int): The buffering strategy to use, see :func:`io.open`.
1314 encoding (str, optional): The encoding to use when reading in text mode, see :func:`io.open`.
1315 errors (str, optional): The error handling strategy for decoding errors, see :func:`io.open`.
1316 newline (str, optional): The strategy for handling newlines in text mode, see :func:`io.open`.
1317 total (int, optional): Total number of bytes to read. If none given, os.stat(path).st_size is used.
1318 task_id (TaskID): Task to track. Default is new task.
1319 description (str, optional): Description of task, if new task is created.
1322 BinaryIO: A readable file-like object in binary mode.
1325 ValueError: When an invalid mode is given.
1328 _mode =
"".join(sorted(mode, reverse=
False))
1329 if _mode
not in (
"br",
"rt",
"r"):
1330 raise ValueError(
"invalid mode {!r}".format(mode))
1333 line_buffering = buffering == 1
1334 if _mode ==
"br" and buffering == 1:
1336 "line buffering (buffering=1) isn't supported in binary mode, the default buffer size will be used",
1340 elif _mode
in (
"rt",
"r"):
1342 raise ValueError(
"can't have unbuffered text I/O")
1343 elif buffering == 1:
1348 total = stat(file).st_size
1352 task_id = self.
add_task(description, total=total)
1354 self.
update(task_id, total=total)
1357 handle =
io.open(file,
"rb", buffering=buffering)
1358 reader =
_Reader(handle, self, task_id, close_handle=
True)
1361 if mode
in (
"r",
"rt"):
1367 line_buffering=line_buffering,
1375 Starts a task (used when calculating elapsed time). You may need to call this manually,
1376 if you called ``add_task`` with ``start=False``.
1379 task_id (TaskID): ID of task.
1382 task = self._tasks[task_id]
1389 This will freeze the elapsed time on the task.
1392 task_id (TaskID): ID of task.
1395 task = self._tasks[task_id]
1405 total: Optional[float] =
None,
1406 completed: Optional[float] =
None,
1407 advance: Optional[float] =
None,
1408 description: Optional[str] =
None,
1409 visible: Optional[bool] =
None,
1410 refresh: bool =
False,
1413 """Update information associated with a task.
1416 task_id (TaskID): Task id (returned by add_task).
1417 total (float, optional): Updates task.total if not None.
1418 completed (float, optional): Updates task.completed if not None.
1419 advance (float, optional): Add a value to task.completed if not None.
1420 description (str, optional): Change task description if not None.
1421 visible (bool, optional): Set visible flag if not None.
1422 refresh (bool): Force a refresh of progress information. Default is False.
1423 **fields (Any): Additional data fields required for rendering.
1426 task = self._tasks[task_id]
1429 if total
is not None and total !=
task.total:
1432 if advance
is not None:
1434 if completed
is not None:
1436 if description
is not None:
1438 if visible
is not None:
1448 while _progress
and _progress[0].timestamp < old_sample_time:
1450 if update_completed > 0:
1467 total: Optional[float] =
None,
1469 visible: Optional[bool] =
None,
1470 description: Optional[str] =
None,
1473 """Reset a task so completed is 0 and the clock is reset.
1476 task_id (TaskID): ID of task.
1477 start (bool, optional): Start the task after reset. Defaults to True.
1478 total (float, optional): New total steps in task, or None to use current total. Defaults to None.
1479 completed (int, optional): Number of steps completed. Defaults to 0.
1480 visible (bool, optional): Enable display of the task. Defaults to True.
1481 description (str, optional): Change task description if not None. Defaults to None.
1482 **fields (str): Additional data fields required for rendering.
1486 task = self._tasks[task_id]
1489 if total
is not None:
1492 if visible
is not None:
1496 if description
is not None:
1501 def advance(self, task_id: TaskID, advance: float = 1) ->
None:
1502 """Advance task by a number of steps.
1505 task_id (TaskID): ID of task.
1506 advance (float): Number of steps to advance. Default is 1.
1510 task = self._tasks[task_id]
1518 while _progress
and _progress[0].timestamp < old_sample_time:
1520 while len(_progress) > 1000:
1532 """Refresh (render) the progress information."""
1537 """Get a renderable for the progress display."""
1542 """Get a number of renderables for the progress display."""
1547 """Get a table to render the Progress display.
1550 tasks (Iterable[Task]): An iterable of Task instances, one per row of the table.
1553 Table: A table instance.
1580 """Makes the Progress class itself renderable."""
1588 total: Optional[float] = 100.0,
1590 visible: bool =
True,
1593 """Add a new 'task' to the Progress display.
1596 description (str): A description of the task.
1597 start (bool, optional): Start the task immediately (to calculate elapsed time). If set to False,
1598 you will need to call `start` manually. Defaults to True.
1599 total (float, optional): Number of total steps in the progress if known.
1600 Set to None to render a pulsing animation. Defaults to 100.
1601 completed (int, optional): Number of steps completed so far. Defaults to 0.
1602 visible (bool, optional): Enable display of the task. Defaults to True.
1603 **fields (str): Additional data fields required for rendering.
1606 TaskID: An ID you can use when calling `update`.
1625 return new_task_index
1628 """Delete a task if it exists.
1631 task_id (TaskID): A task ID.
1635 del self._tasks[task_id]
1638if __name__ ==
"__main__":
1643 from .panel
import Panel
1644 from .rule
import Rule
1645 from .syntax
import Syntax
1646 from .table
import Table
1649 '''def loop_last(values: Iterable[T]) -> Iterable[Tuple[bool, T]]:
1650 """Iterate and generate a tuple with a flag for last value."""
1651 iter_values = iter(values)
1653 previous_value = next(iter_values)
1654 except StopIteration:
1656 for value in iter_values:
1657 yield False, previous_value
1658 previous_value = value
1659 yield True, previous_value''',
1667 progress_renderables = [
1668 "Text may be printed while the progress bars are rendering.",
1669 Panel(
"In fact, [i]any[/i] renderable will work"),
1670 "Such as [magenta]tables[/]...",
1672 "Pretty printed structures...",
1673 {
"type":
"example",
"text":
"Pretty printed"},
1676 Rule(
"Give it a try!"),
1679 from itertools
import cycle
1681 examples = cycle(progress_renderables)
None __init__(self, Optional[int] bar_width=40, StyleType style="bar.back", StyleType complete_style="bar.complete", StyleType finished_style="bar.finished", StyleType pulse_style="bar.pulse", Optional[Column] table_column=None)
None __init__(self, bool binary_units=False, Optional[Column] table_column=None)
__init__(self, str separator="/", Optional[Column] table_column=None)
Column get_table_column(self)
RenderableType __call__(self, "Task" task)
RenderableType render(self, "Task" task)
None __init__(self, Optional[Column] table_column=None)
TaskID add_task(self, str description, bool start=True, Optional[float] total=100.0, int completed=0, bool visible=True, **Any fields)
None __exit__(self, Optional[Type[BaseException]] exc_type, Optional[BaseException] exc_val, Optional[TracebackType] exc_tb)
RenderableType get_renderable(self)
None reset(self, TaskID task_id, *bool start=True, Optional[float] total=None, int completed=0, Optional[bool] visible=None, Optional[str] description=None, **Any fields)
None remove_task(self, TaskID task_id)
BinaryIO wrap_file(self, BinaryIO file, Optional[int] total=None, *Optional[TaskID] task_id=None, str description="Reading...")
Iterable[RenderableType] get_renderables(self)
None stop_task(self, TaskID task_id)
None start_task(self, TaskID task_id)
None __init__(self, *Union[str, ProgressColumn] columns, Optional[Console] console=None, bool auto_refresh=True, float refresh_per_second=10, float speed_estimate_period=30.0, bool transient=False, bool redirect_stdout=True, bool redirect_stderr=True, Optional[GetTimeCallable] get_time=None, bool disable=False, bool expand=False)
None update(self, TaskID task_id, *Optional[float] total=None, Optional[float] completed=None, Optional[float] advance=None, Optional[str] description=None, Optional[bool] visible=None, bool refresh=False, **Any fields)
Iterable[ProgressType] track(self, Union[Iterable[ProgressType], Sequence[ProgressType]] sequence, Optional[float] total=None, Optional[TaskID] task_id=None, str description="Working...", float update_period=0.1)
Tuple[ProgressColumn,...] get_default_columns(cls)
RenderableType __rich__(self)
None advance(self, TaskID task_id, float advance=1)
List[TaskID] task_ids(self)
Table make_tasks_table(self, Iterable[Task] tasks)
"Progress" __enter__(self)
__init__(self, RenderableType renderable="", *Optional[Column] table_column=None)
__init__(self, str spinner_name="dots", Optional[StyleType] style="progress.spinner", float speed=1.0, TextType finished_text=" ", Optional[Column] table_column=None)
None set_spinner(self, str spinner_name, Optional[StyleType] spinner_style="progress.spinner", float speed=1.0)
None __init__(self, str text_format="[progress.percentage]{task.percentage:>3.0f}%", str text_format_no_percentage="", StyleType style="none", JustifyMethod justify="left", bool markup=True, Optional[Highlighter] highlighter=None, Optional[Column] table_column=None, bool show_speed=False)
text_format_no_percentage
Text render_speed(cls, Optional[float] speed)
Optional[float] remaining(self)
Optional[float] time_remaining(self)
GetTimeCallable _get_time
Optional[float] speed(self)
Optional[float] elapsed(self)
None __init__(self, str text_format, StyleType style="none", JustifyMethod justify="left", bool markup=True, Optional[Highlighter] highlighter=None, Optional[Column] table_column=None)
__init__(self, bool compact=False, bool elapsed_when_finished=False, Optional[Column] table_column=None)
None __init__(self, "Progress" progress, _I reader)
None __exit__(self, Optional[Type[BaseException]] exc_type, Optional[BaseException] exc_val, Optional[TracebackType] exc_tb)
bytes read(self, int size=-1)
None __exit__(self, Optional[Type[BaseException]] exc_type, Optional[BaseException] exc_val, Optional[TracebackType] exc_tb)
readinto(self, Union[bytearray, memoryview, mmap] b)
int seek(self, int offset, int whence=0)
None __init__(self, BinaryIO handle, "Progress" progress, TaskID task, bool close_handle=True)
List[bytes] readlines(self, int hint=-1)
"_Reader" __enter__(self)
bytes readline(self, int size=-1)
None __exit__(self, Optional[Type[BaseException]] exc_type, Optional[BaseException] exc_val, Optional[TracebackType] exc_tb)
__init__(self, "Progress" progress, "TaskID" task_id, float update_period)
"_TrackThread" __enter__(self)
ContextManager[BinaryIO] wrap_file(BinaryIO file, int total, *str description="Reading...", bool auto_refresh=True, Optional[Console] console=None, bool transient=False, Optional[Callable[[], float]] get_time=None, float refresh_per_second=10, StyleType style="bar.back", StyleType complete_style="bar.complete", StyleType finished_style="bar.finished", StyleType pulse_style="bar.pulse", bool disable=False)
Iterable[ProgressType] track(Union[Sequence[ProgressType], Iterable[ProgressType]] sequence, str description="Working...", Optional[float] total=None, bool auto_refresh=True, Optional[Console] console=None, bool transient=False, Optional[Callable[[], float]] get_time=None, float refresh_per_second=10, StyleType style="bar.back", StyleType complete_style="bar.complete", StyleType finished_style="bar.finished", StyleType pulse_style="bar.pulse", float update_period=0.1, bool disable=False, bool show_speed=True)