Search code examples
pythonprogress-barcarriage-returntqdm

Carriage return in tqdm.write()


I am having issues with the usage of a carriage return with tqdm.write()

This code works perfectly, it make an animation of a spinning bar

step = 0
for x in range (0,50):
    animation = {0: '|',
                 1: '/',
                 2: '-',
                 3: '\\'
                 }[step]
    tqdm.write(animation, end='\r')
    step = (step+1) % 4
    time.sleep(0.1)

But if I create progress bar just before :

bar = tqdm(total=100)  # Here
step = 0
for x in range (0,50):
    animation = {0: '|',
                 1: '/',
                 2: '-',
                 3: '\\'
                 }[step]
    tqdm.write(animation, end='\r')
    step = (step+1) % 4
    time.sleep(0.1)

I have just a display of the progress bar.

Any ideas ?


Solution

  • This was reported as an issue in the official tqdm github.

    https://github.com/tqdm/tqdm/issues/520

    The author suggested a correction by using a prefix instead of end

    from time import sleep
    from tqdm import tqdm, trange
    from tqdm._utils import _term_move_up
    
    
    prefix = _term_move_up() + '\r'
    print('')
    for x in trange(50):
        tqdm.write(prefix + "|/-\\"[x % 4])
        sleep(0.1)