4

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?

Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
lo tolmencre
  • 3,804
  • 3
  • 30
  • 60

2 Answers2

6

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)
Sнаđошƒаӽ
  • 16,753
  • 12
  • 73
  • 90
6

Have a look at the discussion here: How to overwrite the previous print to stdout in python?
The following code works in the IDLE environment and command line on Windows 10:

import time

while True:
    print('*', end="\r")
    time.sleep(.5)
    print(' ', end="\r")
    time.sleep(.5)
Community
  • 1
  • 1
Maximilian Peters
  • 30,348
  • 12
  • 86
  • 99