Have you ever executed a script, which required minutes, or even more, to be finished?
I did - and I was always a bit stressed looking at the cursor blinking in the console and not knowing if the program is making any progress, or maybe it stuck in an infinite loop or even got frozen.
That's why I found the tqdm tool very useful. It allows easily add a progress bar to every loop we are executing. The syntax is simple like this:
from tqdm import tqdm def heavy_one(): for i in tqdm(range(int(1e6))): pass heavy_one()
If you wonder what is the int(1e6) check out the bottom of this post.
Output:
All you need is to import the tqdm module and wrap any iterable you want with it.
Explanation what is the difference between iterable and iterator here [to be done].
So you can wrap e.g. list: tqdm([1,2,...,1000000])
or range generator tqdm(range(1e6))
We can make it even easier, using the trange function, also provided by tqdm. This function combines together the tqdm and range.
from tqdm import trange def heavy_one(): for i in trange(int(1e6)): heavy_one()
Using trange we can also add a progress bar description, simply by providing desc parameter.
for i in trange(int(1e6), desc='Progress bar:'):
Ok, and what about nested loops? Yep, tqdm can handle them as well!
from tqdm import trange def heavy_one(): for i in trange(int(3), desc='Outside bar:'): for j in trange(1000000, desc='Inside bar:'): pass heavy_one()
Output:
So, these are the basics. If you want to play with the other possibilities the library offers, check out the tqdm documentation here.
And by the way. Sometimes we need to iterate through big set of data, but who likes to type zeros, and count if for sure he typed nine, not eight of them?
Instead of this you can use the exponential notation. I think you agree that int(1e9) looks much cooler (and more Pythonic) than 1000000000.
Brak komentarzy:
Prześlij komentarz