Track progress with tqdm in Python while loop

If you're working on a project that involves a lot of data processing, you may find yourself running into long-running while loops. It can be helpful to track the progress of these loops as they're running, so you know how much work has been done and how long you might have to wait for the loop to finish. One way to do this in Python is with the tqdm library.

To use tqdm in a while loop, you'll first need to install the library with pip. Once installed, you can import tqdm and use it to wrap your loop code. The tqdm library provides a progress bar that will update with each iteration of the loop, giving you a visual indication of how much progress has been made.

Here's an example of how to use tqdm in a while loop:



import time
from tqdm import tqdm

count = 0
total = 100

while count < total:
    time.sleep(0.1) # simulate some work being done
    count += 1
    progress = count / total
    tqdm.write("Progress: {:.2%}".format(progress))

In this example, we're simulating some work being done inside the loop with a time.sleep() call. We're also keeping track of the progress as a percentage of the total work to be done. The tqdm.write() function is used to output the progress to the console.

When you run this code, you'll see a progress bar that updates with each iteration of the loop. The progress bar will show you how much work has been done and how much is left to do, giving you a clear indication of how long the loop might take to complete.

In conclusion, using tqdm in a while loop can be a helpful way to track progress and get a sense of how long your code might take to run. By wrapping your loop code with tqdm, you can easily add a progress bar that updates in real-time, giving you a clear sense of how much work has been done and how much is left to do.

Click to rate this post!
[Total: 0 Average: 0]

Related posts

Leave a Reply

Your email address will not be published. Required fields are marked *

Go up

Below we inform you of the use we make of the data we collect while browsing our pages. You can change your preferences at any time by accessing the link to the Privacy Area that you will find at the bottom of our main page. More Information