3

I want to show the progress bar in a single line. I have written the code

from tqdm import tqdm
from time import sleep
def test():  
     my_list = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']
     for i in tqdm(my_list):
         print(i)
         sleep(.1)

I get the output as follows:

enter image description here

It shows the incremental progress in separate lines. Is there any way to get the progress bar to show progress in the same line as shown below?

enter image description here

I tried removing the print statement. Result as follows:

enter image description here

ted
  • 13,596
  • 9
  • 65
  • 107
  • Not sure why this was marked as a duplicate, these are different questions. One is for printing additional content with a progress bar and the other is for capturing input when using a progress bar. – aviso Dec 17 '22 at 13:11

4 Answers4

1

Your statement print(i) is polluting the output. Remove it.

jurez
  • 4,436
  • 2
  • 12
  • 20
1

Just end your print with end="\033[K".

from tqdm import tqdm
from time import sleep


def test():
    my_list = ["a", "b", "c", "d", "a", "b", "c", "d", "a", "b", "c", "d"]
    for i in tqdm(my_list):
        print(i, end="\033[K")
        sleep(0.1)
Paweł Kowalski
  • 524
  • 3
  • 9
0

tldr: Use tqdm.write instead of print

This is due to you using print. Since tqdm is a very simple progress bar (no curses, only uses the standard output), it can only print on the current line. Since you are using print, you change the current line.

If you still need to print messages to stdout, you can use the .write method of tqdm instead, like this:

 from tqdm import tqdm
 from time import sleep
 def test():  
     my_list = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']
     for i in tqdm(my_list):
         tqdm.write(i)
         sleep(.1)

See more details here:

https://github.com/tqdm/tqdm#writing-messages

tbrugere
  • 755
  • 7
  • 17
  • Or use [Enlighten](https://pypi.org/project/enlighten) instead which handles this automatically – aviso Dec 17 '22 at 13:31
0

Not using the print(i)

 from tqdm import tqdm
    from time import sleep
    def test():  
        my_list = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd', 'a', 'b', 'c', 'd']
        for i in tqdm(my_list):
            sleep(.1)
        
test()
Will
  • 1,619
  • 5
  • 23