Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 669
lo tolmencre Avatar asked Dec 14 '22 07:12

lo tolmencre


1 Answers

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)
like image 138
Sнаđошƒаӽ Avatar answered Jan 06 '23 05:01

Sнаđошƒаӽ