Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Progress bar for a "for" loop in Python script

I am trying to use a progress bar in a python script that I have since I have a for loop that takes quite a bit of time to process. I have looked at other explanations on here already but I am still confused. Here is what my for loop looks like in my script:

for member in members:     url = "http://api.wiki123.com/v1.11/member?id="+str(member)      header = {"Authorization": authorization_code}     api_response = requests.get(url, headers=header)     member_check = json.loads(api_response.text)     member_status = member_check.get("response")  

I have read a bit about using the progressbar library but my confusion lies in where I have to put the code to support a progress bar relative to my for loop I have included here.

like image 832
user7681184 Avatar asked Apr 06 '17 15:04

user7681184


People also ask

How do I loop a progress bar in Python?

Instead of printing out indices or other info at each iteration of your Python loops to see the progress, you can easily add a progress bar. wrap the object on which you iterate with pbar() . and it will display a progress that automatically updates itself after each iteration of the loop.

What is tqdm () in Python?

tqdm is a library in Python which is used for creating Progress Meters or Progress Bars. tqdm got its name from the Arabic name taqaddum which means 'progress'. Implementing tqdm can be done effortlessly in our loops, functions or even Pandas.

What Python package can be used to create a progress bar?

For Python 3 compatibility, try progressbar2 package. The code above will work with it.

HOW IS for loop executed in Python?

for loops are used when you have a block of code which you want to repeat a fixed number of times. The for-loop is always used in combination with an iterable object, like a list or a range. The Python for statement iterates over the members of a sequence in order, executing the block each time.


1 Answers

Using tqdm:

from tqdm import tqdm  for member in tqdm(members):     # current contents of your for loop 

tqdm() takes members and iterates over it, but each time it yields a new member (between each iteration of the loop), it also updates a progress bar on your command line. That makes this actually quite similar to Matthias' solution (printing stuff at the end of each loop iteration), but the progressbar update logic is nicely encapsulated inside tqdm.

like image 58
Jon Avatar answered Oct 13 '22 20:10

Jon