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

1
  • 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, 2022 at 13:11

4 Answers 4

1

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

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)
1

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()
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

1
  • Or use Enlighten instead which handles this automatically
    – aviso
    Dec 17, 2022 at 13:31

Not the answer you're looking for? Browse other questions tagged or ask your own question.