### Python Progressbar Example Usage Source: https://github.com/wolph/python-progressbar/blob/develop/docs/progressbar.bar.md Demonstrates the basic usage of the ProgressBar class, including starting, updating, and finishing the progress bar. This is useful for tracking the progress of long-running operations in Python scripts. ```python >>> pbar = ProgressBar().start() >>> for i in range(100): ... # do something ... pbar.update(i + 1) >>> pbar.finish() ``` -------------------------------- ### ProgressBar Start Method Source: https://github.com/wolph/python-progressbar/blob/develop/docs/progressbar.bar.md The `start` method initializes the progress bar, begins time measurement, and displays the bar at 0%. It can take `max_value` and an `init` flag to control re-initialization. ```python pbar = ProgressBar() pbar.start(max_value=100, init=True) ``` -------------------------------- ### Test Runner for Progressbar Examples (Python) Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md A utility function to run specific example functions from the progressbar library based on command-line arguments. If no arguments are provided, all examples are executed. Requires 'sys' and assumes 'examples' list is defined. ```python import sys # Assuming 'examples' is a list of functions like format_custom_text, simple_api_example, etc. # For a complete runnable example, you'd need to define 'examples' and import necessary functions. def test(*tests) -> None: if tests: no_tests = True for example in examples: for test in tests: if test in example.__name__: example() no_tests = False break if no_tests: for example in examples: print('Skipping', example.__name__) else: for example in examples: example() if __name__ == '__main__': try: test(*sys.argv[1:]) except KeyboardInterrupt: sys.stdout.write('\nQuitting examples.\n') ``` -------------------------------- ### Start ProgressBar Source: https://github.com/wolph/python-progressbar/blob/develop/docs/progressbar.md Starts measuring time and initializes the progress bar at 0%. It can be restarted with the 'init' parameter. The function returns the progress bar instance for chaining. ```python pbar = ProgressBar().start() for i in range(100): # do something pbar.update(i + 1) pbar.finish() ``` -------------------------------- ### ProgressBar Start Source: https://github.com/wolph/python-progressbar/blob/develop/docs/progressbar.md Starts measuring time and initializes the progress bar at 0%. It can optionally reset the progress bar and accept a maximum value. ```APIDOC ## POST /progressbar/start ### Description Starts measuring time, and prints the bar at 0%. It returns self so you can use it like this: `pbar = ProgressBar().start()`. ### Method POST ### Endpoint /progressbar/start ### Parameters #### Query Parameters - **max_value** (float | None) - Optional - The maximum value of the progressbar. - **init** (bool) - Optional - (Re)Initialize the progressbar, this is useful if you wish to reuse the same progressbar but can be disabled if data needs to be persisted between runs, defaults to True. ### Request Body None ### Request Example None ### Response #### Success Response (200) Indicates that the progress bar has been successfully started. #### Response Example ```json { "message": "ProgressBar started successfully." } ``` ``` -------------------------------- ### Granular Progress Bar Examples Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Demonstrates the GranularBar widget, which allows for finer-grained progress visualization using different sets of character markers. This example shows multiple GranularBar instances with varying marker sets and styles. Requires 'progressbar' and 'time'. ```python import progressbar import time widgets = [ progressbar.GranularBar(markers=' ▏▎▍▌▋▊▉█', left='', right='|'), progressbar.GranularBar(markers=' ▁▂▃▄▅▆▇█', left='', right='|'), progressbar.GranularBar(markers=' ▖▌▛█', left='', right='|'), progressbar.GranularBar(markers=' ░▒▓█', left='', right='|'), progressbar.GranularBar(markers=' ⡀⡄⡆⡇⣇⣧⣷⣿', left='', right='|'), progressbar.GranularBar(markers=' .oO', left='', right=''), ] for _ in progressbar.progressbar(list(range(100)), widgets=widgets): time.sleep(0.03) for _ in progressbar.progressbar(iter(range(100)), widgets=widgets): time.sleep(0.03) ``` -------------------------------- ### Start ProgressBar Source: https://github.com/wolph/python-progressbar/blob/develop/docs/progressbar.md Initializes and starts the ProgressBar, setting the time measurement and displaying the bar at 0%%. It accepts an optional `max_value` and can be configured to reinitialize the progress bar for reuse. The method returns the ProgressBar instance itself, allowing for chained method calls. ```python pbar = ProgressBar().start(max_value=100) for i in range(100): pbar.update(i + 1) pbar.finish() ``` -------------------------------- ### Incrementing Progress Bar with Percentage and Bar Widgets Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md This example illustrates creating a progress bar with `Percentage` and `Bar` widgets. It demonstrates the convenient `+=` operator for incrementing the progress bar's value and the `start()` and `finish()` methods for controlling its lifecycle. ```python import progressbar import time bar = progressbar.ProgressBar( widgets=[ progressbar.Percentage(), progressbar.Bar(), ], max_value=10, ).start() for _ in range(10): time.sleep(0.1) bar += 1 bar.finish() ``` -------------------------------- ### Basic Progress Bar Example Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Demonstrates the fundamental usage of the ProgressBar class with Percentage and Bar widgets. It initializes a progress bar, updates it iteratively, and finishes it. This is a foundational example for understanding progress bar creation and updates. ```python import progressbar import time widgets = [progressbar.Percentage(), progressbar.Bar()] bar = progressbar.ProgressBar(widgets=widgets, max_value=10).start() for i in range(10): # do something time.sleep(0.1) bar.update(i + 1) bar.finish() ``` -------------------------------- ### Progress Bar Shortcut Example Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Shows a concise way to create and use a progress bar with the `progressbar.progressbar()` shortcut function. This method simplifies the common case of iterating over a sequence with a progress indicator. It's ideal for quick implementations. ```python import progressbar import time for _ in progressbar.progressbar(range(10)): time.sleep(0.1) ``` -------------------------------- ### Percentage Label Bar Example Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md A simple progress bar example using PercentageLabelBar, which displays the progress as a percentage. This is a straightforward way to show task completion. Requires 'progressbar' and 'time'. ```python import progressbar import time widgets = [progressbar.PercentageLabelBar()] bar = progressbar.ProgressBar(widgets=widgets, max_value=10).start() for i in range(10): # do something time.sleep(0.1) bar.update(i + 1) bar.finish() ``` -------------------------------- ### Double Progress Bar with Reverse Bar Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Demonstrates a progress bar setup with both a standard forward bar and a ReverseBar, indicating progress from both ends. This can be useful for visualizing tasks with distinct start and end phases. Requires 'progressbar' and 'time'. ```python import progressbar import time widgets = [ progressbar.Bar('>'), ' ', progressbar.ETA(), ' ', progressbar.ReverseBar('<'), ] bar = progressbar.ProgressBar(widgets=widgets, max_value=1000).start() for i in range(100): # do something time.sleep(0.01) bar.update(10 * i + 1) ``` -------------------------------- ### Progress Bar with ETA, AbsoluteETA, and AdaptiveETA Widgets Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md This example configures a progress bar with `Percentage`, `ETA`, `AbsoluteETA`, and `AdaptiveETA` widgets. It initializes the bar and then updates it iteratively, allowing observation of how each ETA widget calculates and displays remaining time. ```python import progressbar import time widgets = [ 'Test: ', progressbar.Percentage(), ' | ETA: ', progressbar.ETA(), ' | AbsoluteETA: ', progressbar.AbsoluteETA(), ' | AdaptiveETA: ', progressbar.AdaptiveETA(), ] bar = progressbar.ProgressBar(widgets=widgets, max_value=50).start() for i in range(50): time.sleep(0.1) bar.update(i + 1) bar.finish() ``` -------------------------------- ### Fast Progress Bar Update Example Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Illustrates how to update a progress bar very quickly, which can sometimes lead to flickering in the console. It uses the `force=True` argument in the `update` method to ensure updates are always rendered. This example is useful for testing performance and visual behavior. ```python import progressbar with progressbar.ProgressBar(widgets=[progressbar.Bar()]) as bar: for i in range(100): bar.update(int(i / 10), force=True) ``` -------------------------------- ### Progress Bar with Adaptive and Standard ETA (Python) Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Shows how to use `AdaptiveETA` and `ETA` widgets along with `Timer` for comprehensive time estimation in a progress bar. This example works with a generator function. Requires the 'progressbar' library. ```python import progressbar import time def eta_on_generators(): def gen(): for _ in range(200): yield None widgets = [ progressbar.AdaptiveETA(), ' ', progressbar.ETA(), ' ', progressbar.Timer(), ] bar = progressbar.ProgressBar(widgets=widgets) for _ in bar(gen()): time.sleep(0.02) ``` -------------------------------- ### Basic Progress Bar Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Demonstrates the most basic usage of a progress bar without any specific widgets. It starts, updates iteratively, and finishes. The library defaults to a simple progress indicator. ```python import progressbar import time @example def basic_progress() -> None: bar = progressbar.ProgressBar().start() for i in range(10): time.sleep(0.1) bar.update(i + 1) bar.finish() ``` -------------------------------- ### Progress Bar with Counter and Percentage (Python) Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Demonstrates a progress bar using `Counter`, `Percentage`, and `SimpleProgress` widgets. This example also utilizes a generator function to yield progress. Requires the 'progressbar' library. ```python import progressbar import time def percentage_on_generators(): def gen(): for _ in range(200): yield None widgets = [ progressbar.Counter(), ' ', progressbar.Percentage(), ' ', progressbar.SimpleProgress(), ' ', ] bar = progressbar.ProgressBar(widgets=widgets) for _ in bar(gen()): time.sleep(0.02) ``` -------------------------------- ### Job Status Bar Example Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Shows how to implement a job status bar using the `JobStatusBar` widget. This widget is designed to display distinct statuses (e.g., success, failure, pending) for a task. The example redirects stdout to capture print statements within the progress bar context. ```python import progressbar import random import time with progressbar.ProgressBar( redirect_stdout=True, widgets=[progressbar.widgets.JobStatusBar('status')], ) as bar: for _ in range(30): print('random', random.random()) if random.random() > 0.66: bar.increment(status=True) elif random.random() > 0.5: bar.increment(status=False) else: bar.increment(status=None) time.sleep(0.1) ``` -------------------------------- ### Multi-Range Progress Bar Example Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Shows how to use the MultiRangeBar widget to display progress across multiple segments, each with its own marker. This is useful for visualizing different stages or components of a task. Requires 'progressbar', 'time', and 'random'. ```python import progressbar import time import random markers = [ '\x1b[32m█\x1b[39m', # Done '\x1b[33m#\x1b[39m', # Processing '\x1b[31m.\x1b[39m', # Scheduling ' ', # Not started ] widgets = [progressbar.MultiRangeBar('amounts', markers=markers)] amounts = [0] * (len(markers) - 1) + [25] with progressbar.ProgressBar(widgets=widgets, max_value=10).start() as bar: while True: incomplete_items = [ idx for idx, amount in enumerate(amounts) for _ in range(amount) if idx != 0 ] if not incomplete_items: break which = random.choice(incomplete_items) amounts[which] -= 1 amounts[which - 1] += 1 bar.update(amounts=amounts, force=True) time.sleep(0.02) ``` -------------------------------- ### ProgressBar Class Methods Source: https://github.com/wolph/python-progressbar/blob/develop/docs/progressbar.md Documentation for the core ProgressBar class, including its start, stop, and update methods. ```APIDOC ## ProgressBar Class Methods ### Description Provides methods to control the lifecycle and updates of a progress bar. ### Methods - `start()`: Starts measuring time and initializes the progress bar. - `stop(timeout)`: Stops the progress bar, optionally with a timeout. - `update()`: Updates the progress bar to a new value. ### Parameters #### start() * **max_value** (int) - Optional - The maximum value of the progress bar. * **init** (bool) - Optional - (Re)Initialize the progress bar. #### stop(timeout) * **timeout** (float | None) - Optional - The timeout duration. #### update() * (No specific parameters documented for update in this context. ### Request Example ```python >>> from progressbar import ProgressBar >>> pbar = ProgressBar().start() >>> for i in range(100): ... # do something ... pbar.update(i + 1) >>> pbar.finish() ``` ### Response #### Success Response (200) - **None** - These methods typically do not return a value directly related to success status, but modify the progress bar's state. #### Response Example (No specific response examples provided for these methods as they operate on the progress bar object itself.) ``` -------------------------------- ### Multi-Bar Progress Display Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Illustrates how to manage and display multiple progress bars simultaneously using `progressbar.MultiBar`. This is useful for tracking the progress of several independent tasks concurrently. Note: This example may be skipped on Windows due to threading incompatibilities. ```python import progressbar import os import random import time if os.name == 'nt': print('Skipping multibar example on Windows due to threading incompatibilities with the example code.') else: BARS = 5 N = 50 def do_something(bar): for _ in bar(range(N)): time.sleep(random.random() * 0.1) with progressbar.MultiBar() as multibar: bar_labels = [] for i in range(BARS): bar_label = f'Bar #{i:d}' bar_labels.append(bar_label) assert multibar[bar_label] is not None for _ in range(N * BARS): time.sleep(0.005) bar_i = random.randrange(0, BARS) bar_label = bar_labels[bar_i] multibar[bar_label].increment() ``` -------------------------------- ### Simple Progress Bar API Usage (Python) Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md A basic example demonstrating the simple API of `progressbar.ProgressBar` to create a progress bar with a custom fill character. It iterates a specified number of times with a short delay. Requires the 'progressbar' library. ```python import progressbar import time def simple_api_example() -> None: bar = progressbar.ProgressBar(widget_kwargs=dict(fill='█')) for _ in bar(range(200)): time.sleep(0.02) ``` -------------------------------- ### Custom Text Formatting Progress Bar (Python) Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Illustrates how to use `FormatCustomText` to create a progress bar with custom text fields. This example displays 'Spam' and 'eggs' values that can be dynamically updated. Requires the 'progressbar' library. ```python import progressbar import time def format_custom_text() -> None: format_custom_text = progressbar.FormatCustomText( 'Spam: %(spam).1f kg, eggs: %(eggs)d', dict( spam=0.25, eggs=3, ), ) bar = progressbar.ProgressBar( widgets=[ format_custom_text, ' :: ', progressbar.Percentage(), ] ) for i in bar(range(25)): format_custom_text.update_mapping(eggs=i * 2) time.sleep(0.1) ``` -------------------------------- ### Simple Progress Bar Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md A minimal example of a progress bar using only the SimpleProgress widget. It displays the current and total number of items processed. The progress bar is initialized with a maximum value and updated in a loop. ```python import progressbar import time @example def simple_progress() -> None: bar = progressbar.ProgressBar( widgets=[progressbar.SimpleProgress()], max_value=17, ).start() for i in range(17): time.sleep(0.1) bar.update(i + 1) bar.finish() ``` -------------------------------- ### GranularBar Widget Markers - Python Source: https://github.com/wolph/python-progressbar/blob/develop/docs/progressbar.md Illustrates the use of the GranularBar widget, which allows for progress display at a sub-character level using various marker sets. It lists examples of different marker styles. ```python # Example markers: # Smooth: ' ▏▎▍▌▋▊▉█' (default) # Bar: ' ▁▂▃▄▅▆▇█' # Snake: ' ▖▌▛█' # Fade in: ' ░▒▓█' # Dots: ' ⡀⡄⡆⡇⣇⣧⣷⣿' # Growing circles: ' .oO' ``` -------------------------------- ### Basic File Transfer Progress Bar Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Illustrates a progress bar with widgets for percentage, bar, estimated time of arrival (ETA), and file transfer speed. It simulates a file transfer process and updates the bar accordingly. The example also shows how to handle updates exceeding the defined maximum value. ```python import progressbar import time @example def basic_file_transfer() -> None: widgets = [ 'Test: ', progressbar.Percentage(), ' ', progressbar.Bar(marker='0', left='[', right=']'), ' ', progressbar.ETA(), ' ', progressbar.FileTransferSpeed(), ] bar = progressbar.ProgressBar(widgets=widgets, max_value=500) bar.start() # Go beyond the max_value for i in range(100, 501, 50): time.sleep(0.1) bar.update(i) bar.finish() ``` -------------------------------- ### Initialize and Manually Control ProgressBar in Python Source: https://github.com/wolph/python-progressbar/blob/develop/docs/progressbar.bar.md Demonstrates how to initialize a ProgressBar and manually control its updates and completion. This method is useful when the total number of items is known and progress can be explicitly tracked. The `start()`, `update()`, and `finish()` methods provide granular control over the progress bar's lifecycle. ```python >>> progress = ProgressBar().start() >>> for i in range(100): ... progress.update(i + 1) ... # do something >>> progress.finish() ``` -------------------------------- ### Compare ETA Algorithms with Multiple Estimation Widgets Source: https://context7.com/wolph/python-progressbar/llms.txt This example showcases different ETA (Estimated Time of Arrival) calculation algorithms available in the library: `ETA`, `AdaptiveETA`, and `AbsoluteETA`. It displays them side-by-side for comparison. ```python import time import progressbar widgets = [ progressbar.Percentage(), ' | ETA: ', progressbar.ETA(), ' | Adaptive: ', progressbar.AdaptiveETA(), ' | Absolute: ', progressbar.AbsoluteETA(), ] bar = progressbar.ProgressBar(widgets=widgets, max_value=50).start() for i in range(50): time.sleep(0.1) bar.update(i + 1) bar.finish() # Output: 50% | ETA: 0:00:25 | Adaptive: 0:00:23 | Absolute: 14:30:45 ``` -------------------------------- ### Threaded Progress Bars Management with Python Source: https://github.com/wolph/python-progressbar/blob/develop/README.rst This Python example shows how to manage multiple progress bars concurrently from separate threads using the `progressbar` library. A `Worker` thread class is defined, which takes a `ProgressBar` instance and increments it in a loop. The main part of the script initializes multiple progress bars with distinct line offsets and starts a `Worker` thread for each. ```python import random import threading import time import progressbar BARS = 5 N = 100 # Create the bars with the given line offset bars = [] for line_offset in range(BARS): bars.append(progressbar.ProgressBar(line_offset=line_offset, max_value=N)) class Worker(threading.Thread): def __init__(self, bar): super().__init__() self.bar = bar def run(self): for i in range(N): time.sleep(random.random() / 25) self.bar.update(i) for bar in bars: Worker(bar).start() print() ``` -------------------------------- ### Initialize and Use ProgressBar Source: https://github.com/wolph/python-progressbar/blob/develop/docs/progressbar.bar.md Demonstrates how to initialize a ProgressBar, update its progress iteratively, and then finish it. This is a common pattern for tracking the progress of long-running tasks in Python. ```python from progressbar import ProgressBar pbar = ProgressBar().start() for i in range(100): # do something pbar.update(i + 1) pbar.finish() ``` -------------------------------- ### Combine Progressbar with Standard Print Output (Python) Source: https://github.com/wolph/python-progressbar/blob/develop/README.rst Demonstrates how to integrate a progress bar with standard `print` statements, ensuring that both progress updates and regular output are displayed correctly. The `redirect_stdout=True` argument is key here. Requires `progressbar` and `time`. ```python import time import progressbar for i in progressbar.progressbar(range(100), redirect_stdout=True): print('Some text', i) time.sleep(0.1) ``` -------------------------------- ### Colored Progress Bar Example Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Illustrates how to create a progress bar with custom colors for text and the bar marker. It uses ANSI escape codes to define colors for the 'Colorful example' label and the '#' marker. This enhances the visual appeal of the console output. ```python import progressbar import time widgets = [ '\x1b[33mColorful example\x1b[39m', progressbar.Percentage(), progressbar.Bar(marker='\x1b[32m#\x1b[39m'), ] bar = progressbar.ProgressBar(widgets=widgets, max_value=10).start() for i in range(10): time.sleep(0.1) bar.update(i + 1) bar.finish() ``` -------------------------------- ### Initialize Logging with Stderr Wrapping for Progressbars (Python) Source: https://github.com/wolph/python-progressbar/blob/develop/README.rst Illustrates the correct sequence for initializing logging when using progress bars, ensuring that `stderr` is wrapped before the `StreamHandler` is set up. This prevents output buffering issues. Requires `progressbar`, `logging`, and `time`. ```python import time import logging import progressbar progressbar.streams.wrap_stderr() logging.basicConfig() for i in progressbar.progressbar(range(10)): logging.error('Got %d', i) time.sleep(0.2) ``` -------------------------------- ### Initialize or Re-initialize ProgressBar Source: https://github.com/wolph/python-progressbar/blob/develop/docs/progressbar.bar.md Shows how to use the `init()` method to reset a ProgressBar to its original state. This is useful if you need to reuse an existing ProgressBar instance for a new task. ```python >>> progress = ProgressBar() >>> # ... perform some operations ... >>> progress.init() >>> # ProgressBar is now reset to its initial state ``` -------------------------------- ### progressbar.base Module Source: https://github.com/wolph/python-progressbar/blob/develop/docs/index.md Documentation for the 'base' module, including classes like FalseMeta, IO, and TextIO, which handle fundamental progress bar operations. ```APIDOC ## FalseMeta ### Description A meta class that does not perform any actions. ### Method N/A ### Endpoint N/A ### Parameters None ### Request Example None ### Response None ## IO Class ### Description Represents an input/output stream with various methods for stream manipulation. ### Methods - **close()**: Closes the stream. - **closed** (property): Returns True if the stream is closed, False otherwise. - **fileno()**: Returns the file descriptor. - **flush()**: Flushes the stream buffer. - **isatty()**: Returns True if the stream is a TTY device, False otherwise. - **mode** (property): The mode in which the stream was opened. - **name** (property): The name of the stream. - **read()**: Reads from the stream. - **readable()**: Returns True if the stream can be read from, False otherwise. - **readline()**: Reads a single line from the stream. - **readlines()**: Reads all lines from the stream. - **seek()**: Changes the stream's position. - **seekable()**: Returns True if the stream supports seeking, False otherwise. - **tell()**: Returns the current stream position. - **truncate()**: Truncates the stream. - **writable()**: Returns True if the stream can be written to, False otherwise. - **write()**: Writes to the stream. - **writelines()**: Writes a list of lines to the stream. ### Parameters None ### Request Example None ### Response None ## TextIO Class ### Description Represents a text-based input/output stream. ### Properties - **buffer**: The underlying binary buffer. - **encoding**: The encoding used for the stream. - **errors**: The error handling scheme. - **line_buffering**: Whether line buffering is enabled. - **newlines**: The newline characters used. ### Method N/A (Primarily property-based) ### Parameters None ### Request Example None ### Response None ## Undefined ### Description A singleton representing an undefined value. ### Method N/A ### Endpoint N/A ### Parameters None ### Request Example None ### Response None ## UnknownLength ### Description A special value indicating an unknown length for a progress bar. ### Method N/A ### Endpoint N/A ### Parameters None ### Request Example None ### Response None ``` -------------------------------- ### Reaching Maximum Progress Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md This example shows a basic progress bar reaching its maximum value. It's a fundamental demonstration of the library's core functionality. ```python import progressbar @example def reaching_maximum() -> None: pass # This is a placeholder for the actual code which is missing in the input. ``` -------------------------------- ### DataTransferBar Defaults Source: https://github.com/wolph/python-progressbar/blob/develop/docs/progressbar.bar.md Illustrates how to use `DataTransferBar`, which provides sensible defaults suitable for downloads and data transfer operations, assuming byte-based values. ```python from progressbar import DataTransferBar dtb = DataTransferBar() dtb.start() ``` -------------------------------- ### Wrap Iterable with Python Progressbar Source: https://github.com/wolph/python-progressbar/blob/develop/docs/usage.md This example shows how to wrap an iterable with the Python Progressbar to display progress during iteration. It requires the 'progressbar' library and 'time' for simulation. ```python import time import progressbar bar = progressbar.ProgressBar() for i in bar(range(100)): time.sleep(0.02) ``` -------------------------------- ### Filling Bar with Animated Marker Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Combines a filling bar with an animated marker. The marker itself animates, and the bar fills up to indicate progress. This example uses a '#' character as the fill for the bar. ```python import progressbar import time @example def filling_bar_animated_marker() -> None: bar = progressbar.ProgressBar( widgets=[ progressbar.Bar( marker=progressbar.AnimatedMarker(fill='#'), ), ] ) for _ in bar(range(15)): time.sleep(0.1) ``` -------------------------------- ### Python Progressbar with Custom Widgets Source: https://github.com/wolph/python-progressbar/blob/develop/docs/usage.md Example of customizing the appearance of the Python Progressbar using a list of widgets like Timer, Bar, and ETA. Requires 'progressbar' and 'time'. ```python import time import progressbar bar = progressbar.ProgressBar(widgets=[ ' [', progressbar.Timer(), '] ', progressbar.Bar(), ' (', progressbar.ETA(), ') ', ]) for i in bar(range(20)): time.sleep(0.1) ``` -------------------------------- ### progressbar.utils Module Source: https://github.com/wolph/python-progressbar/blob/develop/docs/index.md Documentation for the 'utils' module, including helper classes like AttributeDict and StreamWrapper for utility functions. ```APIDOC ## AttributeDict ### Description A dictionary subclass that allows attribute-style access to its items. ### Method N/A ### Endpoint N/A ### Parameters None ### Request Example None ### Response None ## StreamWrapper Class ### Description Wraps standard streams (stdout, stderr) to capture output and manage exception handling. ### Methods - **capturing** (property): Returns True if capturing is active. - **excepthook()**: Custom exception hook. - **flush()**: Flushes the stream buffer. - **listeners**: A list of registered listeners. - **needs_clear()**: Checks if the stream needs clearing. - **original_excepthook**: Stores the original exception hook. - **start_capturing()**: Starts capturing output. - **stderr**: The wrapped stderr stream. - **stdout**: The wrapped stdout stream. - **stop_capturing()**: Stops capturing output. - **unwrap()**: Unwraps the stream wrapper. - **unwrap_excepthook()**: Unwraps the custom exception hook. - **unwrap_stderr()**: Unwraps the stderr stream. - **unwrap_stdout()**: Unwraps the stdout stream. - **update_capturing()**: Updates capturing state. - **wrap()**: Wraps a stream. - **wrap_excepthook()**: Wraps the exception hook. - **wrap_stderr()**: Wraps the stderr stream. - **wrap_stdout()**: Wraps the stdout stream. - **wrapped_excepthook**: Stores the wrapped exception hook. - **wrapped_stderr**: Stores the wrapped stderr stream. - **wrapped_stdout**: Stores the wrapped stdout stream. ### Parameters None ### Request Example None ### Response None ``` -------------------------------- ### Progress Bar with Right Justification Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Demonstrates how to control the justification of the progress bar within the terminal using the `term_width` and `left_justify` parameters. This example sets `left_justify` to `False` to right-justify the bar. ```python import progressbar import time @example def with_right_justify() -> None: with progressbar.ProgressBar( max_value=10, term_width=20, left_justify=False ) as progress: assert progress.term_width is not None for i in range(10): progress.update(i) ``` -------------------------------- ### Demonstration of Various ETA Widget Types Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md This code explores different Estimated Time of Arrival (ETA) widgets available in the library, including `ETA`, `AdaptiveETA`, `SmoothingETA` (with different smoothing factors), `AbsoluteETA`, and `FileTransferSpeed`. It configures a progress bar with all these widgets to visualize their behavior over time. ```python import progressbar import time widgets = [ progressbar.Percentage(), ' ETA: ', progressbar.ETA(), ' Adaptive : ', progressbar.AdaptiveETA(), ' Smoothing(a=0.1): ', progressbar.SmoothingETA(smoothing_parameters=dict(alpha=0.1)), ' Smoothing(a=0.9): ', progressbar.SmoothingETA(smoothing_parameters=dict(alpha=0.9)), ' Absolute: ', progressbar.AbsoluteETA(), ' Transfer: ', progressbar.FileTransferSpeed(), ' Adaptive T: ', progressbar.AdaptiveTransferSpeed(), ' ', progressbar.Bar(), ] bar = progressbar.ProgressBar(widgets=widgets, max_value=500) bar.start() for i in range(500): if i < 100: time.sleep(0.02) elif i > 400: time.sleep(0.1) else: time.sleep(0.01) bar.update(i + 1) bar.finish() ``` -------------------------------- ### Multi-Progress Bar Example Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Illustrates the use of MultiProgressBar to manage and display progress for multiple independent jobs simultaneously. Each job's progress is aggregated into an overall progress bar. Requires 'progressbar', 'time', and 'random'. ```python import progressbar import time import random jobs = [ # Each job takes between 1 and 10 steps to complete [0, random.randint(1, 10)] for _ in range(25) # 25 jobs total ] widgets = [ progressbar.Percentage(), ' ', progressbar.MultiProgressBar('jobs', fill_left=left), ] max_value = sum([total for progress, total in jobs]) with progressbar.ProgressBar(widgets=widgets, max_value=max_value) as bar: while True: incomplete_jobs = [ idx for idx, (progress, total) in enumerate(jobs) if progress < total ] if not incomplete_jobs: break which = random.choice(incomplete_jobs) jobs[which][0] += 1 progress = sum([progress for progress, total in jobs]) bar.update(progress, jobs=jobs, force=True) time.sleep(0.02) ``` -------------------------------- ### Flush Standard Output for Progressbars with Logging (Python) Source: https://github.com/wolph/python-progressbar/blob/develop/README.rst Demonstrates how to manually flush standard output to ensure proper display of progress bars when logging is involved. This is crucial in environments like Jupyter notebooks that buffer stdout. It requires the `progressbar` library. ```python import sys sys.stdout.flush() ``` -------------------------------- ### Basic Progress Bar with Animated Marker Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Demonstrates a basic progress bar using a custom animated marker. The marker uses 'x' as the fill character and applies ANSI color codes for visual feedback. Requires the 'progressbar' library and 'time' for simulation. ```python import progressbar import time widgets = [ progressbar.Bar( marker=progressbar.AnimatedMarker( fill='x', fill_wrap='\x1b[32m{}\x1b[39m', marker_wrap='\x1b[31m{}\x1b[39m', ) ), ] bar = progressbar.ProgressBar(widgets=widgets, max_value=10).start() for i in range(10): # do something time.sleep(0.1) bar.update(i + 1) bar.finish() ``` -------------------------------- ### Templated Progress Bar Suffix Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md Utilizes the `progressbar.progressbar()` shortcut with a suffix that includes a format string. This allows dynamic information, such as elapsed time, to be displayed at the end of the progress bar. The example shows how to format `seconds_elapsed`. ```python import progressbar import time for _ in progressbar.progressbar(range(10), suffix='{seconds_elapsed:.1}'): time.sleep(0.1) ``` -------------------------------- ### Create Multiple Threaded Progressbars (Python) Source: https://github.com/wolph/python-progressbar/blob/develop/README.rst Demonstrates how to manage multiple, potentially threaded, progress bars concurrently using `progressbar.MultiBar`. This allows for simultaneous progress tracking of different tasks. Requires `progressbar`, `threading`, `time`, and `random`. ```python import random import threading import time import progressbar BARS = 5 N = 50 def do_something(bar): for i in bar(range(N)): # Sleep up to 0.1 seconds time.sleep(random.random() * 0.1) # print messages at random intervals to show how extra output works if random.random() > 0.9: bar.print('random message for bar', bar, i) with progressbar.MultiBar() as multibar: for i in range(BARS): # Get a progressbar bar = multibar[f'Thread label here {i}'] # Create a thread and pass the progressbar threading.Thread(target=do_something, args=(bar,)).start() ``` -------------------------------- ### Install Development Requirements Source: https://github.com/wolph/python-progressbar/blob/develop/CONTRIBUTING.rst Installs necessary development dependencies, including testing tools like flake8 and tox, from a requirements file. This ensures the development environment is properly configured for testing across different Python versions. ```bash pip install -r tests/requirements.txt ``` -------------------------------- ### Stderr Redirection with Progressbar Source: https://github.com/wolph/python-progressbar/blob/develop/docs/examples.md This example demonstrates redirecting standard error to the progress bar using `redirect_stderr=True`. Similar to stdout redirection, this allows error messages to be captured and displayed alongside the progress bar without interfering with its rendering. ```python import progressbar import sys with progressbar.ProgressBar(redirect_stderr=True) as progress: print('', file=sys.stderr) progress.update(0) ```