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

1
  • Here's the RESULT of my "efforts"...(simple and dumb but hey, I learned something new). Commented Jul 2, 2013 at 19:39

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

That worked very well, thank you! Can you tell me why it is this way?
Thank you to both of you! I tried to search here for an answer but I must have not used the right keywords...
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)

3 Comments

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.
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.
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.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.