3.3 KiB
Diese Konversation wurde mit Duck.ai (https://duck.ai) unter Verwendung des o3-mini-Modells von OpenAI generiert. KI-Chats zeigen möglicherweise falsche oder anstößige Informationen an (weitere Informationen siehe https://duckduckgo.com/duckai/privacy-terms).
====================
Benutzereingabe 1 von 2 - 5.6.2025, 02:27:36: in Rust, what can I use to display multiple progress bars in the terminal?
o3-mini: You can use the indicatif crate, which provides a MultiProgress type that lets you manage and display multiple progress bars concurrently in a terminal.
Below is a simple example of how to use indicatif’s MultiProgress to display multiple progress bars:
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use std::{thread, time::Duration};
fn main() {
// Create a MultiProgress container.
let m = MultiProgress::new();
// Create several progress bars.
let pb1 = m.add(ProgressBar::new(100));
pb1.set_style(
ProgressStyle::default_bar()
.template("{msg} {bar:40.cyan/blue} {pos:>3}/{len:3}")
.expect("Failed to set progress bar style"),
);
pb1.set_message("Downloading");
let pb2 = m.add(ProgressBar::new(50));
pb2.set_style(
ProgressStyle::default_bar()
.template("{msg} {bar:40.green/black} {pos:>3}/{len:3}")
.expect("Failed to set progress bar style"),
);
pb2.set_message("Processing");
// Optionally, spawn threads to update the progress bars concurrently.
let h1 = std::thread::spawn(move || {
for i in 0..=100 {
pb1.set_position(i);
thread::sleep(Duration::from_millis(50));
}
pb1.finish_with_message("Download complete");
});
let h2 = std::thread::spawn(move || {
for i in 0..=50 {
pb2.set_position(i);
thread::sleep(Duration::from_millis(100));
}
pb2.finish_with_message("Processing complete");
});
// Wait for threads to complete. MultiProgress takes care of rendering.
h1.join().expect("Thread 1 panicked");
h2.join().expect("Thread 2 panicked");
// You may also iterate on the multi-progress which blocks until all bars finish:
// m.join().unwrap();
}
Steps Explained
-
MultiProgress Container:
Create aMultiProgressinstance which is used to manage multiple progress bars. -
Progress Bars:
Create individual progress bars usingMultiProgress::add(). You can customize each progress bar with a message, style, and length. -
Concurrent Updates:
The example spawns two threads – one for each progress bar. Each thread updates its progress bar independently usingset_position()and finishes the progress bar withfinish_with_message(). -
Thread Joining:
Ensure the main thread waits for the worker threads to complete to prevent the program from exiting prematurely.
Installation
Make sure to add indicatif to your Cargo.toml:
[dependencies]
indicatif = "0.17" # or the latest version available on crates.io
This crate provides many options for customizing and using progress bars in a concurrent and effective manner. The documentation is available at indicatif on docs.rs for further details and advanced usage.