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?

4
  • Your program works fine for me. It has to be a problem with your environment. Are you using idle? Apr 17, 2016 at 9:37
  • 1
    Why not use print? Apr 17, 2016 at 9:40
  • no, I am using KDE terminal "Konsole" Apr 17, 2016 at 9:44
  • because print always prints a newline Apr 17, 2016 at 9:44

2 Answers 2

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)
1
  • prints repetitive * on Windows, end='\r' works for me Apr 17, 2016 at 10:04
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)
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.