1

I am trying to print a string letter by letter (with a pause in between each print) onto the terminal screen and I want it to all be on the same line.

I currently have this:

sleepMode = "SLEEP MODE..."
activ = "ACTIVATE!"
for l in sleepMode:
    print(l, end=" ")
    sleep(0.1)
sleep(2) 
for l in activ:
    print(l, end=" ")
    sleep(0.1)

For some reason this doesn't sleep in between prints in the loop, rather it seems to wait until the loop is complete before printing all of it out at once.

I want it to look like it is being "typed" on the screen in real time.

Any suggestions?

Thanks! Zach

zkirkland
  • 12,175
  • 3
  • 16
  • 18
  • Here's the [RESULT](https://github.com/zkirkland/RedBull/blob/master/redbull.py) of my "efforts"...(simple and dumb but hey, I learned something new). – zkirkland Jul 02 '13 at 19:39

2 Answers2

3

try flushing it

for l in activ:
    print(l, end=" ")
    sys.__stdout__.flush()
    sleep(0.1)

no idea if it will work since I am assuming you are using py3x and it works fine in my system with or without the flush

flush just forces the output buffer to write to the screen ... normally it will wait until it has some free time to dump it to the screen. but sleep was locking it. so by flushing it you are forcing the content to the screen now instead of letting the internal scheduler do it ... at least thats how I understand it. Im probably missing some nuance

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179
0

The following works:

import time
import sys
sleepMode = "SLEEP MODE..."
activ = "ACTIVATE!"
for l in sleepMode:
    sys.stdout.write(l);
    time.sleep(0.1)
time.sleep(2) 
print
for l in activ:
    sys.stdout.write(l);
    time.sleep(0.1)
Floris
  • 45,857
  • 6
  • 70
  • 122
  • This actually does not work for me. It does the same thing as before. It waits until the sleep function completes and then outputs the entire thing at once. – zkirkland Jul 02 '13 at 19:30
  • That's strange - it must be implementation dependent. It was working fine for me. In that case the `flush` approach is the way to go then - but I guess you already know that. I wonder what is different between your version of Python and mine. – Floris Jul 02 '13 at 19:57
  • I have python 3.2 on windows 7. Just tested it in Ubuntu 12.04 with same version of python and works well with flush function. – zkirkland Jul 02 '13 at 22:12