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наđошƒаӽ
  • 15,289
  • 12
  • 72
  • 86
lo tolmencre
  • 3,606
  • 2
  • 22
  • 52

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наđошƒаӽ
  • 15,289
  • 12
  • 72
  • 86
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
  • 27,890
  • 12
  • 74
  • 90