2

Recently I've picked up Python 3.4 programming and I read this other question regarding how to printing slowly (Simulate typing), and used a similar def in my code.

import time

def type(str):
     for letter in str:
        print(letter, end='')
        time.sleep(0.02)
    print("\n")

type("This sentence is typed.")

It all worked fine in IDLE, but once I tried running it using Windows Command prompt, CMD waits the time it took IDLE to type it (half a second in this case) and then spits it out as if it had been printed.

I figured the time.sleep statement was broken one way or another, although

print("One")
time.sleep(2)
print("Two")

worked just fine.

Is there any way of printing one letter at a time with a short interval between the letters, or is it simply not possible?

Thanks in advance!

Community
  • 1
  • 1
Ridir
  • 23
  • 6

1 Answers1

2

Try forcing a flush on stdout after each character. The problem is that stdout is normally buffered until either a newline, EOF or a certain number of bytes have been output.

import time
import sys

def type(str):
    for letter in str:
        print(letter, end='')
        sys.stdout.flush()
        time.sleep(0.02)
    print("\n")

type("This sentence is typed.")

Alternately, in Python3, as @PeterWood mentioned, you can change your print so that it auto-flushes.

        print(letter, end='', flush=True)
merlin2011
  • 71,677
  • 44
  • 195
  • 329