0

I created a very primitive progress bar/wheel in Python which looks like this:

if round(i/len(some_list)*100, 1).is_integer():
    for frame in cycle(r'-\|/-\|/'):
        print("\r", frame, " ", round(i/len(some_list)*100,1), "%", sep = "", end = "", flush=True)

updated code for easier replication (added as per request in the comments)

from itertools import cycle
import random as rd

rnd_lst = []
for i in range(0,5000):
    n = rd.randint(1,30)
    rnd_lst.append(n)
    
def pb_wheel(lst):

    tick=0

    for frame in cycle(r'-\|/-\|/'):  
        
        if tick < len(lst):
            print("\r", frame, " ", round(tick/len(lst)*100, 2), "%", sep = "", end = "", flush=True)
            tick += 1
        else:
            print("\r", "100%", flush=True)
            print("\n", "Done")
            break      

pb_wheel(rnd_lst)

It works reasonably well at first with the output looking like expected:

\ 0.0%

But after the initial success, after about 5-6 seconds parts of the pb/pw get duplicated:

- 0.0% % % 0.0% - 0.0% 0.0% 

I assume that the flush is too slow. I tested this by adding a time delay time.sleep(0.01) which reduces the occurrence of duplications but does not quite eliminate them. As I don't actually want to artificially slow down the code I wanted to ask if there is a solution to this problem.

I am working with Spyder on a Windows OS.

D.J
  • 1,180
  • 1
  • 8
  • 17
  • It sounds like you have some kind of race condition. Are you calling this method from multiple threads? – Selcuk Jul 19 '21 at 15:20
  • i am not. i would like to implement some parallel/multithread processing later but i am not too skilled with python yet – D.J Jul 19 '21 at 15:33
  • 2
    Well done for not dumping all the code from your project onto the question :) But I think we need a little more code to be able to replicate the problem; would you be able to make a small function that calls this function and demonstrates the problem? – JeffUK Jul 19 '21 at 15:41
  • Maybe instead of relying on `print` to flush, you should do it manually? [How can I flush the output of the print function?](https://stackoverflow.com/q/230751/5987) – Mark Ransom Jul 19 '21 at 16:01
  • @JeffUK sorry for the late answer/update of the question. i put in a working example that, at least on my computer, replicates the problem – D.J Jul 20 '21 at 10:18

0 Answers0