pythonbusyindicator

Make a blinking busy indicator on python shell


I want to make * flash on the command line in a 1 second interval.

import time
from sys import stdout

while True:
    stdout.write(' *')
    time.sleep(.5)
    stdout.write('\r  ')
    time.sleep(.5)

All I get is a blank line, no flashing *.

Why is that?


Solution

  • Check this out. This will print * on a line at intervals of 0.5 second, and show for 0.5 second (flashing as you called it)

    import time
    
    while True:
         print('*', flush=True, end='\r')
         time.sleep(0.5)
         print(' ', flush=True, end='\r')
         time.sleep(0.5)
    

    Note that this doesn't work in IDLE, but with cmd it works fine.

    Without using two print statements, you can do it this way:

    import time
    
    i = '*'
    while True:
        print('{}\r'.format(i), end='')
        i = ' ' if i=='*' else '*'
        time.sleep(0.5)