Search code examples
pythonprogress-bartqdm

progress bar in script Python


I have to ask something that other guys did, but I haven't find an answer (maybe is stupid).

I need to implement a progress bar in my script python, ia red about tqdm and i like a lot that library because it has nice colours and the bar is well-structured, instead of a simple [---------].

a simple script that I saw is this:

from tqdm import tqdm
for i in tqdm(range(10000)):
    pass

but my question is: where do I insert my code?? seems stupid but I tried several times and the bar won't go. simply stays at 0% and until my script ends.

Another point is that if I try also that simple code, everytime the bar update itself, it creates a new line with a new bar. so how can I have a single bar that fill when time passes?

thanks a lot, and of course evry kind of support and advice will be appreciated

EDIT---- If my code is:

alphabetic = ['a','b','c','d','e','f','g','h','i','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0-9']

for lett in alphabetic: lista_pag_success = pr.find_following_page('/artisti/lettera/'+lett) 

artisti=[] 
linksss=[] 

for i in lista_pag_success: 
       artisti, linksss = pr.crawl_canzoni_it(i) 

I have to put all this code in the tqdm() function? I have to pass just an iterable? but what if I have I case like this? lista_pag_success and artisti, linksss are three lists - this is a code for a simple crawler –


Solution

  • Your iterable over which you want to monitor progress, should replace range(10000) in the sample code you posted.

    For example, if you have a list of numbers, [1, 4, 9, 10], and you want to find the square of each number, you would iterate over tqdm([1, 4, 9, 10]) and perform your calculation inside the for loop, i.e.:

    squared_nums = []
    for num in tqdm([1, 4, 9, 10]):
        squared_nums.append(num * num)
    print(squared_nums)
    

    This would generate output like:

    100%|████████████████████████████████████████████████████| 4/4 [00:00<00:00, 14820.86it/s]
    [1, 16, 81, 100]
    

    Of course, in this simple case, it could also be written using a list comprehension:

    squared_nums = [num * num for num in tqdm([1, 4, 9, 10])]